简体   繁体   English

用Jest进行单元测试Redux异步功能

[英]Unit Testing redux async function with Jest

I'm pretty new to unit testing so please pardon any noobness. 我对单元测试还很陌生,所以请原谅。

I have a file api.js which has all the API call functions for the app. 我有一个文件api.js ,其中包含该应用程序的所有API调用函数。 Each function returns its promise. 每个函数返回其诺言。 Here's how it looks: 外观如下:

api.js api.js

const api = {
  getData() {
    return superagent
      .get(apiUrl)
      .query({
        page: 1,
      });
  },
}

Now coming to the redux async action that i'm trying to test. 现在来我要测试的redux异步操作。 It looks something like this: 看起来像这样:

getDataAction.js 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.`);
              }
            });
    }
}

Now, In my test file, I've tried this: 现在,在我的测试文件中,我已经尝试过:

getDataAction.test.js getDataAction.test.js

jest.mock('api.js');
describe('getData Action', () => {
  it('gets the data', () => {
    expect(store.dispatch(getData())).toEqual(expectedAction);
  });
});

This, throws me an error: 这给我抛出一个错误:

TypeError: Cannot read property 'end' of undefined

What am I doing wrong ? 我究竟做错了什么 ? Now i'm able to mock api.js with default automocker of Jest, but how do I handle the case of running callback function with end ? 现在,我可以使用Jest的默认自动模拟程序来模拟api.js,但是如何处理以end运行回调函数的情况? Thanks a lot for any help ! 非常感谢您的帮助!

Your mock of api needs to return a function that returns an object that has the end function: 您的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();
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM