mfr*_*het 0 javascript unit-testing reactjs jestjs
我试图在jest.mock上做一个间谍,(我不喜欢你想要的东西,我更喜欢"老派"的方式)
这样我就进行了以下测试:
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();
});
});
Run Code Online (Sandbox Code Playgroud)
这是我想要测试的代码(不完整,测试驱动):
export const fetchRemote = slug => {
return dispatch => {
dispatch(loading());
return fetch(Constants.URL + slug)
};
};
Run Code Online (Sandbox Code Playgroud)
我的fetch模拟实现(实际上是节点获取)是:
export default () => Promise.resolve({json: () => []});
Run Code Online (Sandbox Code Playgroud)
模拟效果很好,它很好地取代了通常的实现.
我的主要问题是,我怎样才能窥探那个模拟函数?我需要测试它已被调用好的参数,我绝对不知道如何做到这一点.在测试实现中有一个"???" 我不知道如何创造有关的间谍.
任何的想法 ?
在你的模拟实现中,你可以做到
const fetch = jest.fn(() => Promise.resolve({json: () => []}));
module.exports = fetch;
Run Code Online (Sandbox Code Playgroud)
现在在你的测试中你需要做
const fetchMock = require('node-fetch'); // this will get your mock implementation not the actual one
...
...
expect(fetchMock).toBeCalledWith(Constants + slug);
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助