使用 Jest 对 redux 异步函数进行单元测试

Unit Testing redux async function with Jest

我是单元测试的新手,所以请原谅任何菜鸟。

我有一个文件 api.js,其中包含应用程序的所有 API 调用函数。每个功能 returns 它的承诺。外观如下:

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 处理 运行 回调函数的情况?非常感谢您的帮助!

您的 api 模拟需要 return 一个函数,该函数 return 是一个具有 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();
  });
});