使用jest.mock传递超出范围的变量

时间:2017-11-20 17:27:42

标签: javascript react-native jestjs

我有一个模拟对象,我用来模拟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的同时使代码正常工作?

1 个答案:

答案 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时,它就有效了。