Passing out-of-scope variable with jest.mock

Viewed 17281

I have a mock object that I am using to mock react-native:

const MyMock = {
    MockA: {
        methodA: jest.genMockFn()
    },
    MockB: {
        ObjectB: {
            methodA: jest.genMockFn(),
            methodB: jest.genMockFn(),
        }
    }
};


jest.mock('react-native', () => {
    return MyMock;
});

I am declaring the object outside of jest.mock because I also need it later on in my tests:

describe('MyClass', () => {
     beforeEach(() => {
         MyMock.MockB.ObjectB.methodA.mockClear();
         MyMock.MockB.ObjectB.methodB.mockClear();
     });
     //some other code

I get this error:

The module factory of jest.mock() is not allowed to reference any out-of-scope variables.

The problem is that I declare MyMock outside of jest.mock. But I have no choice as far as I can see.

So how can I make the code work while keeping MyMock outside of jest.mock?

1 Answers

I hadn't read the error message fully. On the last line(slightly obscured) there is this:

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.

So when I changed MyMock to for instance mockMyMock, it worked.

Related