knee-cola / jest-mock-axios

Axios mock for Jest
252 stars 42 forks source link

Question: Why use this instead of the built in mock that comes with Jest? #60

Closed cmacdonnacha closed 4 years ago

cmacdonnacha commented 4 years ago

Hey,

I have been mocking my axios method via Jest for a while now but came across this package and I've wondered what it does for you that the built in Jest mocking doesn't?

In my React component I simply have:

jest.mock('axios');

const fetchMockPosts = () => {
  axiosMock.get.mockResolvedValueOnce({
      data: {
        posts: ['post1', 'post2']
      }
  });
};

test('should find and display posts', async () => {
  // Setup
  fetchMockPosts();
  render(<Page />);

  // Wait for loading text to disappear so we know the mocked posts have been fetched and displayed
  await waitForElementToBeRemoved(() => screen.queryByText('Loading posts'));

  // Find the post title
  expect(screen.getByText('post1')).toBeInTheDocument();
});
kingjan1999 commented 4 years ago

Hi,

what it does for you that the built in Jest mocking doesn't?

In short? Nothing. This library uses Jest's mocking support as well, so everything this library does you can do by your own as well.

However, depending on your needs, there might be situations were using this library is advantageous to using your approach (which is also the approach outlined in the Jest docs).

Precisely, the control flow for "your" approach looks like this:

  1. Set up mocked responses (fetchMockPosts) ("Arrange")
  2. Execute code under test (render(<Page />)) ("Act")
  3. Do assertions. (expect().toBe) ("Assert")

    This should work most of the time and follows the AAA-pattern.

This library is to / can be used in a slightly different flow:

  1. Execute code under test up to the first axios call
  2. Mock response
  3. Continue code execution, jump to 2 for every subsequent axios call
  4. Assertions

This flow might help you with situations where you have multiple axios calls / the number of axios calls are unknown and where you want to response on-the-fly to calls instead of setting them up before hand. Apart from that, this library offers some convenience methods to respond to specific requests (getReqByMatchUrl) instead of all / the first one as in mockResolvedValueOnce (not saying you can't do this without this lib).

Hope this helps!

cmacdonnacha commented 4 years ago

That's a great explanation @kingjan1999 thanks!