1
我对单元测试很新,所以请原谅任何noobness。单元测试异步函数与Jest
我有一个文件api.js
它具有应用程序的所有API调用函数。每个函数都返回它的承诺。下面是它的外观:
api.js
const api = {
getData() {
return superagent
.get(apiUrl)
.query({
page: 1,
});
},
}
现在来,我试图测试Redux的异步操作。它看起来是这样的:
getDataAction.js
export function getData(){
return dispatch => {
api.getData()
.end((err, data) => {
if (err === null && data !== undefined) {
console.log(data);
} else if (typeof err.status !== 'undefined') {
throw new Error(`${err.status} Server response failed.`);
}
});
}
}
现在,在我的测试文件,我已经试过这样:
getDataAction.test.js
jest.mock('api.js');
describe('getData Action',() => {
it('gets the data',() => {
expect(store.dispatch(getData())).toEqual(expectedAction);
});
});
这,给我一个错误:
TypeError: Cannot read property 'end' of undefined
我在做什么错?现在我可以使用Jest的默认automocker模拟api.js,但是如何处理与end
一起运行回调函数的情况?非常感谢您的帮助!