我有一个模拟对象,我用来模拟react-native
:
const MyMock = {
MockA: {
methodA: jest.genMockFn()
},
MockB: {
ObjectB: {
methodA: jest.genMockFn(),
methodB: jest.genMockFn(),
}
}
};
jest.mock('react-native', () => {
return MyMock;
});
我在jest.mock
之外声明对象,因为我以后在测试中也需要它:
describe('MyClass', () => {
beforeEach(() => {
MyMock.MockB.ObjectB.methodA.mockClear();
MyMock.MockB.ObjectB.methodB.mockClear();
});
//some other code
我收到此错误:
The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables.
问题是我在MyMock
之外宣布jest.mock
。但就我所见,我别无选择。
那么如何在MyMock
之外保持jest.mock
的同时使代码正常工作?
答案 0 :(得分:15)
我没有完全阅读错误消息。在最后一行(略微模糊)有这样的:
Note: This is a precaution to guard against uninitialized mock variables. If it is ensured that the mock is required lazily, variable names prefixed with `mock` are permitted.
因此,当我将MyMock
更改为例如mockMyMock
时,它就有效了。