用Jest模拟基于承诺的请求 [英] Mocking promised based request with Jest
问题描述
我正在尝试使用Jest对功能进行单元测试,并且在处理jest模拟模块时遇到了一些麻烦(相当于nodejs世界中的rewire或proxyquire).
I'm trying to unit test a function using Jest, and I'm having some trouble dealing with jest mock modules (the equivalent of rewire or proxyquire in nodejs world).
我实际上是在尝试测试是否已使用某些参数在模拟模块上调用了间谍程序.这是我要测试的功能.
I'm actually trying to test that a spy has been called on the mocked module with some parameters. Here's the function that I want to test.
注意:当前测试仅涉及"fetch(...)"部分,我试图测试是否已使用好参数调用了提取.
NB : the current test only concerns the "fetch(...)" part, I m trying to test that fetch has been called with the good parameter.
export const fetchRemote = slug => {
return dispatch => {
dispatch(loading());
return fetch(Constants.URL + slug)
.then(res => res.json())
.then(cmp => {
if (cmp.length === 1) {
return dispatch(setCurrent(cmp[0]));
}
return dispatch(computeRemote(cmp));
});
};
};
返回的函数充当闭包,因此捕获"我要模拟的节点获取外部模块.
The function returned acts as a closure, and so "captures" the node-fetch external module that I want to mock.
这是我要通过绿色的测试:
Here's the test I m trying to make pass green :
it('should have called the fetch function wih the good const parameter and slug', done => {
const slug = 'slug';
const spy = jasmine.createSpy();
const stubDispatch = () => Promise.resolve({json: () => []});
jest.mock('node-fetch', () => spy);
const dispatcher = fetchRemote(slug);
dispatcher(stubDispatch).then(() => {
expect(spy).toHaveBeenCalledWith(Constants.URL + slug);
done();
});
});
第一个答案对编写测试有很大帮助,我现在有以下内容:
EDIT : The first answer helped a lot concerning writing the test, I have now the following one :
it('should have called the fetch function wih the good const parameter and slug', done => {
const slug = 'slug';
const stubDispatch = () => null;
const spy = jest.mock('node-fetch', () => Promise.resolve({json: () => []}));
const dispatcher = fetchRemote(slug);
dispatcher(stubDispatch).then(() => {
expect(spy).toHaveBeenCalledWith(Constants.URL + slug);
done();
});
});
但是现在,这是我遇到的错误:
But now, here's the error I have :
console.error node_modules/core-js/modules/es6.promise.js:117
Unhandled promise rejection [Error: expect(jest.fn())[.not].toHaveBeenCalledWith()
jest.fn() value must be a mock function or spy.
Received:
object: {"addMatchers": [Function anonymous], "autoMockOff": [Function anonymous], "autoMockOn": [Function anonymous], "clearAllMocks": [Function anonymous], "clearAllTimers": [Function anonymous], "deepUnmock": [Function anonymous], "disableAutomock": [Function anonymous], "doMock": [Function anonymous], "dontMock": [Function anonymous], "enableAutomock": [Function anonymous], "fn": [Function anonymous], "genMockFn": [Function bound getMockFunction], "genMockFromModule": [Function anonymous], "genMockFunction": [Function bound getMockFunction], "isMockFunction": [Function isMockFunction], "mock": [Function anonymous], "resetModuleRegistry": [Function anonymous], "resetModules": [Function anonymous], "runAllImmediates": [Function anonymous], "runAllTicks": [Function anonymous], "runAllTimers": [Function anonymous], "runOnlyPendingTimers": [Function anonymous], "runTimersToTime": [Function anonymous], "setMock": [Function anonymous], "unmock": [Function anonymous], "useFakeTimers": [Function anonymous], "useRealTimers": [Function anonymous]}]
推荐答案
First of all you need to return a promise when testing async code. And your spy needs to return a resolved or rejected promise.
it('should have called the fetch function wih the good const parameter and slug', done => {
const slug = 'successPath';
const stubDispatch = () => Promise.resolve({ json: () => [] });
spy = jest.mock('node-fetch', (path) => {
if (path === Constants.URL + 'successPath') {
return Promise.resolve('someSuccessData ')
} else {
return Promise.reject('someErrorData')
}
});
const dispatcher = fetchRemote(slug);
return dispatcher(stubDispatch).then(() => {
expect(spy).toHaveBeenCalledWith(Constants.URL + slug);
done();
});
});
这篇关于用Jest模拟基于承诺的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!