How do you test a component (say <Person /> in this case) if it renders fully but only after <Loading /> completes, which is after a successful Ajax call?
I am using Jest and Enzyme. With Enzyme, however, the snapshot would be of Person with the Loading component and not the final, rendered state after the Ajax call. I would need to mock my Ajax call, but what would that look like with a mock and then taking a Snapshot after?
class Person extends Component {
...
componentWillMount() {
// ajax call to person data, including ID
// on successful Ajax completion, set state.personID and other values, etc.
axios.get('.../person', {
params: {
AltID: 12345
}
}).then(function (response) {
this.setState({personID: response.data.personID,...});
}).catch(function (error) {
...
});
}
render() {
if (!this.state.personID) {
return (
<div className="App">
<Loader />
</div>);
}
return (
<div className="App">
...
Person ID: {{this.state.personID}}
...
</div>
);
}
}
Enzyme snapshot test (needs embellishing):
describe('Person', () => {
it('renders correctly', () => {
const rendered = renderer.create(<Person />);
expect(rendered.toJSON()).toMatchSnapshot();
});
});
Lastly, a work around such as setting this.setState({personID: value}) in the test is not what I would be looking for, since, in the real unpublished scenario, componentWillMount performs an Ajax call to authenticate the users. Currently, that's getting pushed to an error page.
You can mock api calls https://facebook.github.io/jest/docs/en/tutorial-async.html or you can just make 2 tests, one with the condition being True, and the other with the condition being False. Your api call just changes the state from one state to another so...you need to test if everything renders correctly, according to the state.
Example: