我目前正在使用Jest对我的一个反应服务进行单元测试(使用redux-saga)。这些服务调用的API,选择器和操作不在其他API,选择器和特定于此服务的操作之外。
因此,为了模拟这些外部API,选择器和操作,我使用jest在我的测试文件中模拟它们,如下所示:
// API mock example
jest.mock('../otherFeatureService/api'), () => {
return { myApi: jest.fn() };
}
// reducer mock example
jest.mock('../otherFeatureService/reducer'), () => {
return { isConnected: (fake) => jest.fn(fake) };
}
// API action example
jest.mock('../otherFeatureService/actions'), () => {
return { myAction: () => jest.fn() };
}
除了模拟操作之外,我的测试中一切正常。 但是,当我试图将我的预期结果与我为模拟操作得到的结果进行比较时,我得到了以下消息:
expect(received).toEqual(expected)
Expected value to equal:
{"@@redux-saga/IO": true, "PUT": {"action": [Function mockConstructor], "channel": null}}
Received:
{"@@redux-saga/IO": true, "PUT": {"action": [Function mockConstructor], "channel": null}}
Difference:
Compared values have no visual difference.
您对为什么它不仅仅适用于行动有任何想法吗? (我正在使用来自'redux-saga-testing'的sagaHelper进行测试)
感谢。 printfx000。
答案 0 :(得分:0)
您遇到此问题是因为jest无法区分2个匿名函数。 为了解决这个问题,你需要为mock提供一个命名函数。 因为jest hoist mock声明,你需要在你的mock中声明你的命名函数 。
jest.mock('../selectors', () => {
function mockedMakeSelectCoverageResult() {}
return ({
makeSelectCoverageResult: () => mockedMakeSelectCoverageResult,
});
});
expect(descriptor).toEqual(select(makeSelectCoverageResult()));