Jest.js 监视笑话模拟

iaqfqrcu  于 2022-12-08  发布在  Jest
关注(0)|答案(2)|浏览(270)

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 ?

fdx2calv

fdx2calv1#

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

55ooxyrt

55ooxyrt2#

对于任何仍在搜索内联模拟的人来说,现代的方法是:

const nodeFetch = require("node-fetch")
const fetchSpy = jest.spyOn(nodeFetch, "fetch")
...
expect(fetchSpy).toHaveBeenCalledWith(...)

这样,您就不必创建单独的模拟实现

相关问题