stackjlei stackjlei - 3 months ago 19
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) => {
.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() {
}, 1500);

What is the purpose of using
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.


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.