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
?
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.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With