Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing out-of-scope variable with jest.mock

Tags:

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?

like image 815
octavian Avatar asked Nov 20 '17 17:11

octavian


People also ask

Can I mock a variable in Jest?

If you need to mock a global variable for all of your tests, you can use the setupFiles in your Jest config and point it to a file that mocks the necessary variables. This way, you will have the global variable mocked globally for all test suites.

How do you mock the return value of a function in Jest?

To mock a function's return value in Jest, you first need to import all named exports from a module, then use mockReturnValue on the imported function. You can use the * as <alias> inside an import statement to import all named exports. Then, you need to chain mockReturnValue off of jest.

Does Jest mock get hoisted?

Using with ES module imports​ But often you need to instruct Jest to use a mock before modules use it. For this reason, Jest will automatically hoist jest. mock calls to the top of the module (before any imports).


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.

like image 188
octavian Avatar answered Oct 31 '22 06:10

octavian