监视模拟

Spy on Jest mock

我正在尝试监视 jest.mock,(我不太喜欢 unmock 你想要的东西,我更喜欢 "old school" 方式)

通过这种方式,我将进行以下测试:

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();
            });
        });

这是我要测试的代码(不完整,测试驱动):

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

我的 fetch 模拟实现(实际上是 node-fetch)是:

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

模拟效果很好,它很好地替代了通常的实现。

我的主要问题是,如何监视那个模拟函数?我需要测试它是否已使用正确的参数调用,但我完全不知道该怎么做。在测试实现中有一个“???”而且我不知道如何创建相关间谍。

有什么想法吗?

在您的模拟实现中,您可以

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

现在在你的测试中你需要做

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

希望这对您有所帮助