简体   繁体   English

窥探 Jest 模拟

[英]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)我正在尝试对 jest.mock 进行间谍活动,(我不是 unmock 你想要的东西的忠实粉丝,我更喜欢“老派”的方式)

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:我的 fetch 模拟实现(实际上是 node-fetch)是:

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?我的主要问题是,我怎样才能监视那个被嘲笑的 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?任何想法?

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希望这可以帮助

The modern way for anybody still searching which works with inline mocks as well is just:对于仍在搜索与内联模拟一起使用的任何人的现代方法就是:

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

This way you don't have to create separate mocked implementations这样您就不必创建单独的模拟实现

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM