Skahrz Skahrz - 1 month ago 36
Javascript Question

Spy on Jest mock

I m trying to make a spy on a jest.mock, (I m not a big fan of unmock what you want, I prefer the "old school" way)

This way I m having the following test :

jest.mock('node-fetch');
// ...
it('should have called the fetch function wih the good const parameter and slug', done => {
const slug = 'slug';
const stubDispatch = () => null;
const dispatcher = fetchRemote(slug);
dispatcher(stubDispatch).then(() => {
expect(???).toBeCalledWith(Constants + slug);
done();
});
});


And this is the code I want to test (that is not complete, test driven) :

export const fetchRemote = slug => {
return dispatch => {
dispatch(loading());
return fetch(Constants.URL + slug)
};
};


My mock implementation of fetch (which in fact is node-fetch) is :

export default () => Promise.resolve({json: () => []});


The mock works well, and it well replace the usual implementation.

My main question is, how can I spy on that mocked function ? I need to test that it has been called with the good parameters, and I absolutely dont know how to make that. In the test implementation there is a "???" and I don't know how to create the concerned spy.

Any idea ?

Answer

in your mock implementation, you can do

const fetch = jest.fn(() => Promise.resolve({json: () => []}));
module.exports = fetch;

Now in your test you need to do

const fetchMock = require('node-fetch'); // this will get your mock implementation not the actual one
...
...
expect(fetchMock).toBeCalledWith(Constants + slug);

hope this helps