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

A misty Oxfordshire canal and lock

Say you have this test:

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:

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

Fix 2

Use 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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store