使用Jest测试分派其他2个功能的Redux动作? [英] Testing a Redux action that dispatches 2 other functions with Jest?

查看:81
本文介绍了使用Jest测试分派其他2个功能的Redux动作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数(一个Redux动作),它调用2个函数.我不知道如何用Jest进行测试:

I have a function (a Redux action) which calls 2 functions. I can't figure how how to test this with Jest:

这是我的功能:

import doSomething from 'redux/do-something';
import doSomethingElse from 'redux/do-something-else';

export default () => async dispatch => {
  await dispatch(doSomething());
  dispatch(doSomethingElse());
};

这是我的测试

import doSomething from 'redux/do-something';
import doSomethingElse from 'redux/do-something-else';

import functionToTest from 'redux/function-to-test'

describe("functionToTest", ()=>{
    jest.mock('redux/do-something');
    jest.mock('redux/do-something-else');
    const dispatch = jest.fn();

    test('my test', ()=>{
        functionToTest()(dispatch);
        console.log(dispatch.mock.calls); // This returns an anonymous function
        console.log(doSomething) // This returns undefined 
    })

})

推荐答案

您似乎想模拟do-somethingdo-something-else的默认导出,并测试它们是否被测试代码调度了.

It looks like you are wanting to mock the default export for do-something and do-something-else and test that they get dispatched by the code under test.

如果是这种情况,那么您可以这样做:

If that is the case then you can do it like this:

import functionToTest from 'redux/function-to-test'

jest.mock('redux/do-something', () =>
  () => 'do something mock'
);
jest.mock('redux/do-something-else', () =>
  () => 'do something else mock'
);

describe("functionToTest", () => {
  test('my test', async () => {  // <= async test function
    const dispatch = jest.fn();
    await functionToTest()(dispatch);  // <= await the Promise
    expect(dispatch.mock.calls[0][0]).toBe('do something mock');  // Success!
    expect(dispatch.mock.calls[1][0]).toBe('do something else mock');  // Success!
  });
});

详细信息

您可以将模块工厂函数作为第二个参数传递给jest.mock,并且Jest将使用调用该函数的结果作为在测试期间导入模块时返回的结果.

You can pass a module factory function as the second paramter to jest.mock and Jest will use the result of calling the function as what it gives back when the module is imported during the test.

jest.mock调用被babel-jest挂起,并在代码文件中的所有其他内容之前运行.当在测试函数中定义了jest.mock时,无法吊装 jest.mock调用应移至测试文件的顶级范围.

jest.mock calls get hoisted by babel-jest and run before everything else in the code file. The hoisting doesn't work right when jest.mock is defined in a test function so the jest.mock calls should be moved to the top level scope of the test file.

被测函数为async,因此请使用async测试函数和await Promise来确保其在断言之前已完成.

The function under test is async so use an async test function and await the Promise to make sure it has completed before asserting.

这篇关于使用Jest测试分派其他2个功能的Redux动作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆