
Jest can swap out timers with functions that allow you to control the passage of time. In this article, we learned the three most common ways to mock Axios in Jest:Įach of them has its own advantages and disadvantages, but I suggest starting with the first one without installing any additional external libraries and see if that works well for you. run jest tests sequentially why/how run single file/folder run single test interactive watch mode (filtering by file name, failing tests, test filename regex) running in CI mode Spying, stubbing - become a stub/mock function assertion pro. The native timer functions (i.e., setTimeout(), setInterval(), clearTimeout(), clearInterval()) are less than ideal for a testing environment since they depend on real time to elapse. It's a good practice to mock API calls in tests, not only because we don't want to call the real API, but also to be able to easily test special cases, such as what happens if the request returns 200 or 404 or fails with the "Network Error" message. If any difficulties are encountered, only then see if libraries can help solve them. I suggest starting without any library and see if that works well.
Jest reset mocks install#
If you need to test a simple function that makes a request to an API and returns a response - you probably don't need to install and configure additional libraries, just go with the Way #1 and jest.mock() function.Įxternal libraries provide a lot of useful functionality that makes testing harder cases much easier. This is useful when you want to mock functions in certain test cases and restore the original implementation in others.

mockFn.mockRestore() Does everything that mockFn.mockReset() does, and also restores the original (non-mocked) implementation. The answer is - it depends on the requirements. The mockReset configuration option is available to reset mocks automatically before each test. In this article we learned two ways to mock Axios using external libraries, so it would be good to know which library is more popular and safer to use.Īccording to the NPM Trends, axios-mock-adapter is much more popular with about 570,000 weekly downloads compared to almost 90,000 for jest-mock-axios: Confirm that the request was sent to the correct endpoint and that the correct result is returned.Call the function you are testing ( fetchUsers() in our example).Create a sample response and mock the call to the specific endpoint by using mock.onGet() function.Reset the mocked Axios object by calling: mock.reset() after each test in the afterEach hook, so that the state in the mock is cleared and each test starts fresh.


