我正在尝试使用Jest对一个函数进行单元测试,而且我在处理jest模拟模块时遇到了一些麻烦(相当于nodejs世界中的rewire或proxyquire)。
我实际上是在尝试测试已经使用一些参数在模拟模块上调用间谍。这是我要测试的功能。
注意:当前测试仅涉及“fetch(...)”部分,我试图测试已使用good参数调用fetch。
File "/usr/lib64/python2.7/heapq.py", line 427, in nsmallest
result = _nsmallest(n, it)
File "<stdin>", line 1, in <lambda>
TypeError: bad operand type for unary -: 'unicode'
返回的函数充当闭包,因此“捕获”我想要模拟的节点获取外部模块。
这是我试图通过绿色的测试:
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));
});
};
};
编辑:第一个答案对编写测试有很大帮助,我现在有以下一个:
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();
});
});
但现在,这是我的错误:
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();
});
});
答案 0 :(得分:5)
首先,您需要在testing async code时返回承诺。而你的间谍需要回复已经解决或被拒绝的承诺。
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();
});
});