【问题标题】:Unit Testing functions to check dispatch to be called用于检查要调用的调度的单元测试功能
【发布时间】:2019-11-26 22:20:02
【问题描述】:

store.js

const store = createStore(state,...) 
export default store;

myfunction.js

import store from './store'

const myFunction = async ()=>{
  store.dispatch(...some actions);
};

export default myFunction;

mytest.js

import store from './store';
import myFunction from './myfunction';

describe("myFunction", ()=>{
  it("should call dispatch" ()=>{

    await myFunction()

    // test something like below
    expect(store.dispatch).toBeCalled();

 })
})

您好,我想在 react/redux 应用程序中对我的辅助函数进行单元测试。我在上面创建了一个示例函数来为您提供一些上下文。

如您所见,myFunction 导入 store 并在内部使用 store.dispatch。我想检查store.dispatch 是否已被调用,但我很难做到这一点。模拟似乎不起作用,因为它只模拟在 mytest.js 中导入的实例,而不是在 myFunction.js 中导入的实例

我曾试图像窥探它一样

const spyStore = jest.spyOn(store, "dispatch");

我收到错误说调度未定义。

这种情况有什么线索吗?

非常感谢您的意见。

【问题讨论】:

    标签: reactjs unit-testing testing redux jestjs


    【解决方案1】:

    你试过这样模拟 store 模块吗?

    jest.mock('./store', ()=> ({
       dispatch: jest.fn(),
    }));
    

    【讨论】:

    • 该死的!我一直在使用 jest.doMock 进行斗争,但我想这只是 jest.mock。谢谢一百万!
    猜你喜欢
    • 1970-01-01
    • 2015-07-29
    • 2019-05-07
    • 1970-01-01
    • 2017-10-15
    • 1970-01-01
    • 2022-11-11
    • 2021-10-16
    • 1970-01-01
    相关资源
    最近更新 更多