Jest unit testing: block all outgoing traffic

Viewed 2072

I would like to somehow block all outgoing traffic when running unit tests with jest. Ideally you mock all the modules (or functions that send http requests) including 3rd party ones, but when you are in the process of development you may not be able to mock everything from the start and may accidentally send some data.

If that's not possible with jest, what would then be the best practice to do so? iptables maybe?

1 Answers

There are just few ways for JS code to send request: new XMLHttpRequest, fetch and new WebSocket. Once you mock that in file setup(jest provides single file that will be for sure called before any test is running) you are safe:

window.fetch = jest.fn();

and later in your tests do that like

window.fetch.mockImplementation((url) =>  
   url === 'https://example.org/data' && 
     Promise.resolve({ message: 'wrong', data: 1 })
);
...
expect(window.fetch).toHaveBeenCalledWith('https://example.org/data');
...

For sure it'd be quite large piece of work to do that on your own. So there are particular packages does that for you. Say fetch-mock. My favorite by now is nock that covers both XHR and fetch and provides a lot of utils to cover most possible edge cases while mocking network responses/requests.

Related