Javascript 使用Jest对redux异步函数进行单元测试
我对单元测试还很陌生,所以请原谅我的任何不妥之处 我有一个文件Javascript 使用Jest对redux异步函数进行单元测试,javascript,unit-testing,reactjs,jestjs,superagent,Javascript,Unit Testing,Reactjs,Jestjs,Superagent,我对单元测试还很陌生,所以请原谅我的任何不妥之处 我有一个文件api.js,其中包含应用程序的所有api调用函数。每个函数都返回其承诺。下面是它的外观: api.js 现在来看我要测试的redux异步操作。它看起来像这样: getDataAction.js 现在,在我的测试文件中,我尝试了以下方法: getDataAction.test.js 这给我带来了一个错误: TypeError: Cannot read property 'end' of undefined 我做错了什么?现在我可以用
api.js
,其中包含应用程序的所有api调用函数。每个函数都返回其承诺。下面是它的外观:
api.js
现在来看我要测试的redux异步操作。它看起来像这样:
getDataAction.js
现在,在我的测试文件中,我尝试了以下方法:
getDataAction.test.js
这给我带来了一个错误:
TypeError: Cannot read property 'end' of undefined
我做错了什么?现在我可以用Jest的默认自动模拟程序模拟api.js,但是如何处理使用
end
运行回调函数的情况呢?非常感谢你的帮助 模拟的api
需要返回一个函数,该函数返回具有end
函数的对象:
import api from 'api' //to set the implantation of getData we need to import the api into the test
// this will turn your api into an object with the getData function
// initial this is just a dumb spy but you can overwrite its behaviour in the test later on
jest.mock('api.js', ()=> ({getData: jest.fn()}));
describe('getData Action', () => {
it('gets the data', () => {
const result = {test: 1234}
// for the success case you mock getData so that it returns the end function that calls the callback without an error and some data
api.getData.mockImplementation(() => ({end: cb => cb(null, result)}))
expect(store.dispatch(getData())).toEqual(expectedAction);
});
it('it thows on error', () => {
// for the error case you mock getData so that it returns the end function that calls the callback with an error and no data
api.getData.mockImplementation(() => ({end: cb => cb({status: 'someError'}, null)}))
expect(store.dispatch(getData())).toThrow();
});
});
jest.mock('api.js');
describe('getData Action', () => {
it('gets the data', () => {
expect(store.dispatch(getData())).toEqual(expectedAction);
});
});
TypeError: Cannot read property 'end' of undefined
import api from 'api' //to set the implantation of getData we need to import the api into the test
// this will turn your api into an object with the getData function
// initial this is just a dumb spy but you can overwrite its behaviour in the test later on
jest.mock('api.js', ()=> ({getData: jest.fn()}));
describe('getData Action', () => {
it('gets the data', () => {
const result = {test: 1234}
// for the success case you mock getData so that it returns the end function that calls the callback without an error and some data
api.getData.mockImplementation(() => ({end: cb => cb(null, result)}))
expect(store.dispatch(getData())).toEqual(expectedAction);
});
it('it thows on error', () => {
// for the error case you mock getData so that it returns the end function that calls the callback with an error and no data
api.getData.mockImplementation(() => ({end: cb => cb({status: 'someError'}, null)}))
expect(store.dispatch(getData())).toThrow();
});
});