componentDidMount call a store that call the apifetchVersionsRequest functionfetchVersionsRequest call the api endpoint using Promiseall is updated by store after the promise resolved@observer will call component render again because all was updatedPlease, check the comments
@inject('versionStore') @observer
export default class extends Component {
componentDidMount() {
const { fetch } = this.props.versionStore;
fetch(); // Will call api.fetchVersionsRequest
}
render() {
// all is an array updated after call api.fetchVersionsRequest resolved
const { all } = this.props.versionStore;
// ...
return {all.map(it => <p>{it.name}</p>)}
}
}
How can I test if component is rendering right?
I want to use Snapshot feature, give a list returned by api, the component should be mach the snapshot
My test Home component
it('renders versions', function() {
const versions = [
{ id: 1, name: 'version1' },
{ id: 2, name: 'version2' },
];
api.fetchVersionsRequest = jest.fn(() => {
return Promise.resolve(versions);
});
const wrapper = shallow(<Home {...this.minProps} />);
expect(toJson(wrapper)).toMatchSnapshot(); // PROBLEM Snapshot does not contain any p element
}
Just to show you how to work with promises in jest. You have to return the promise from your test to let jest know that it have to wait for it.
it('renders versions', function() {
const versions = [
{ id: 1, name: 'version1' },
{ id: 2, name: 'version2' },
];
const p = Promise.resolve(versions);
api.fetchVersionsRequest = jest.fn(() => {
return p
});
const wrapper = shallow(<Home {...this.minProps} />);
return p.then(()=>{
expect(toJson(wrapper)).toMatchSnapshot();
})
}
or
it('renders versions', async function() {
const versions = [
{ id: 1, name: 'version1' },
{ id: 2, name: 'version2' },
];
const p = Promise.resolve(versions);
api.fetchVersionsRequest = jest.fn(() => {
return p
});
const wrapper = shallow(<Home {...this.minProps} />);
a
expect(toJson(wrapper)).toMatchSnapshot();
}
It is explained here in the docs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With