Jest unit testing with components that use node-fetch
I like very much the Fetch API and I tend to use it as much as possible also with node components.
The same, of course, is applicable to my favorite testing framework: Jest; it works brilliantly with React but I highly recommend to use it in other environments as well.
Super easy setup, assertion library, mocking framework, snapshot testing and code coverage; all in one platform.
But this post is about a specific use case: how to unit test with Jest node components that use node-fetch
.
There are many libraries that help you to mock fetch
but my favorite in this regard is jest-fetch-mock
; it has a very nice API and it works really well together with Jest and because of that I’d like to use it in a non-in-browser context as well.
So here it is my standard setup in 3 simple steps:
npm install --save-dev jest-fetch-mock
- add or modify your
setupJest.js
file with the following code:
const fetch = require('jest-fetch-mock');jest.setMock('node-fetch', fetch);
3. import node-fetch
in your test file and mock it as you please:
const fetch = require('node-fetch');fetch.mockResponse(JSON.stringify({ message: 'YATTA!' }));
You can also find another example here. I hope this helps.