Two ways to fix the Jest test error “the module factory of `jest.mock()` is not allowed to reference any out-of-scope variables”

Luke Rogerson
1 min readSep 19, 2020

--

A misty Oxfordshire canal and lock
Photo by Simon Godfrey on Unsplash

Say you have this test:

Example test you might write using “jest.mock()”

It’s not going to work…

Jest will complain that:

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

Fix 1

Prepend your jest.fn() variable declaration with mock. So, in the above example, navigateToProfile becomes mockNavigateToProfile:

Prepending our variable declaration with “mock”

Understand why variables that start with the word “mock” solves our scoping error

Fix 2

Use jest.doMock() instead of jest.mock():

Using jest.doMock() instead of jest.mock()

🌻 Note: if you want to use this method, there are some additional steps you’ll first have to follow.

--

--