stackjlei stackjlei - 2 months ago 15
React JSX Question

What is the purpose of using a mock ajax call in testing?

I'm learning about TDD React here and don't understand the below test situation:

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 }
]);
// Overwrite, so we can correctly reason about the count number
// Don't want shared state
wrapper = mount(<UsersListComponent />);
setTimeout(function() {
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();
}, 1500);
});


What is the purpose of using
nock
to fake a request? This request doesn't do anything and I'm not sure where the response goes to. I thought TDD approach is to write the test (the code starting at wrapper), see it fail, and then use a real ajax call in the actual component to test. I don't see what nock does here.

Answer

The purpose of the nock call in your code is to fake an API request. Nock captures / intercepts the call and instead of the actual response it returns a response with fake information.

The title of the test is Correctly updates the state after AJAX call... so the intention is to test whether the state is updated correctly, and not whether the actual API request has been successfully carried out.

This allows you to model and test different scenarios, for example, how your app behaves when receiving different datasets. It also allows you to complete your tests when the actual API may not be ready yet.