Skip to content

Instantly share code, notes, and snippets.

@david-casagrande
Last active July 29, 2016 07:38
Show Gist options
  • Select an option

  • Save david-casagrande/6b6bef8e7cadd353baa6707867b576fe to your computer and use it in GitHub Desktop.

Select an option

Save david-casagrande/6b6bef8e7cadd353baa6707867b576fe to your computer and use it in GitHub Desktop.
react/enzyme/async tdd
// non-async
it('Correctly makes AJAX request in `componentDidMount`', () => {
nock('https://api.github.com')
.get('/users')
.reply(200, [
{ 'name': 'Reign', 'age': 26 }
]);
wrapper = mount(<UsersListComponent />);
// expect nock-request to be called with 'https://api.github.com/users' etc
});
// async
it('Correctly updates the state after AJAX call in `componentDidMount` was made', (done) => {
nock('https://api.github.com')
.get('/users')
.reply(200, [
{ 'name': 'Reign', 'age': 26 }
]);
wrapper = mount(<UsersListComponent />);
wrapper.instance().fetchUsers().end(() => {
expect(wrapper.state().usersList).to.be.instanceof(Array);
expect(wrapper.state().usersList.length).to.equal(1);
expect(wrapper.state().usersList[0].name).to.equal('Reign');
expect(wrapper.state().usersList[0].age).to.equal(26);
nock.cleanAll();
done();
});
});
// updated component methods
componentDidMount() {
this.fetchUsers();
}
fetchUsers() {
return request
.get('https://api.github.com/users')
.end((err, res) => {
if (err) {
console.log(err);
return;
}
this.setState({
usersList: res.body.slice(0)
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment