我在Jest中有以下代码:
const mockOnNextAction = jest.fn(() => {
then: jest.fn();
});
jest.mock('NativeModules', () => {
return {
MyNativeModule: {
onNextAction: mockOnNextAction
}
};
});
MyNativeModule.executeSomeChecks();
expect(NativeModules.MyNativeModule.onNextAction).toHaveBeenCalled();
expect(NativeModules.MyNativeModule.onNextAction().then).toHaveBeenCalled();
在我正在测试的代码中,我想像这样打个电话:
NativeModules.MyNativeModule.onNextAction().then(() => {
//contents of callback function
});
问题是在测试中的代码中我收到此错误:
TypeError: Cannot read property 'then' of undefined
另外,以下打印声明:
console.log("NativeModules.MyNativeModule.onNextAction: " + JSON.stringify(NativeModules.MyNativeModule.onNextAction));
的结果为undefined
为什么onNextAction
未定义?我正在用Jest嘲笑它,所以它应该存在。
答案 0 :(得分:0)
我的模拟有两个问题。
1.我不尊重ES6 lambda函数语法,因此我更改为:() => ({...})
并删除了对象内的;
。
2.我使then
字段引用为同一个变量,否则NativeModules.MyNativeModule.onNextAction().then
将始终是未被调用的新对象。
最后,我的代码如下所示:
const mockThen = jest.fn();
const mockOnNextAction = jest.fn(() => ({
then: mockThen
}));
jest.mock('NativeModules', () => ({
MyNativeModule: {
onNextAction: mockOnNextAction
}
}));