130

I'm trying to mock a call to a service but I'm struggeling with the following message: The module factory of jest.mock() is not allowed to reference any out-of-scope variables.

I'm using babel with ES6 syntax, jest and enzyme.

I have a simple component called Vocabulary which gets a list of VocabularyEntry-Objects from a vocabularyService and renders it.

import React from 'react';
import vocabularyService from '../services/vocabularyService';

export default class Vocabulary extends React.Component {
    render() {

        let rows = vocabularyService.vocabulary.map((v, i) => <tr key={ i } >
            <td>{ v.src }</td>
            <td>{ v.target }</td>
        </tr>);
        // render rows
    }
}

The vocabularyServise ist very simple:

import { VocabularyEntry } from '../model/VocabularyEntry';

class VocabularyService {

    constructor() {
        this.vocabulary = [new VocabularyEntry("a", "b")];
    }
}
export default new VocabularyService();

Now I want to mock the vocabularyService in a test:

import { shallow } from 'enzyme';
import React from 'react';
import Vocabulary from "../../../src/components/Vocabulary ";
import { VocabularyEntry } from '../../../src/model/VocabularyEntry'

jest.mock('../../../src/services/vocabularyService', () => ({

    vocabulary: [new VocabularyEntry("a", "a1")]

}));

describe("Vocabulary tests", () => {

    test("renders the vocabulary", () => {

        let $component = shallow(<Vocabulary/>);

        // expect something

    });
});

Running the test causes an error: Vocabulary.spec.js: babel-plugin-jest-hoist: The module factory of jest.mock() is not allowed to reference any out-of-scope variables. Invalid variable access: VocabularyEntry.

As far as I unterstood, I cannot use the VocabularyEntry because it is not declares (as jest moves the mock definition to the top of the file).

Can anyone please explain how I can fix this? I saw solutions which required the references insinde the mock-call but I do not understand how I can do this with a class file.

Elias
  • 3,592
  • 2
  • 19
  • 42
Ria
  • 1,900
  • 4
  • 14
  • 21

7 Answers7

120

You need to store your mocked component in a variable with a name prefixed by "mock". This solution is based on the Note at the end of the error message I was getting.

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.

import {shallow} from 'enzyme';
import React from 'react';
import Vocabulary from "../../../src/components/Vocabulary ";
import {VocabularyEntry} from '../../../src/model/VocabularyEntry'

const mockVocabulary = () => new VocabularyEntry("a", "a1");

jest.mock('../../../src/services/vocabularyService', () => ({
    default: mockVocabulary
}));

describe("Vocabulary tests", () => {

test("renders the vocabulary", () => {

    let $component = shallow(<Vocabulary/>);

    // expect something

});
Kalle Richter
  • 8,008
  • 26
  • 77
  • 177
maxletou
  • 1,355
  • 1
  • 8
  • 6
71

The problem is that all jest.mock will be hoisted to the top of actual code block at compile time, which in this case is the top of the file. At this point VocabularyEntry is not imported. You could either put the mock in a beforeAll block in your test or use jest.mock like this:

import {shallow} from 'enzyme';
import React from 'react';
import Vocabulary from "../../../src/components/Vocabulary ";
import {VocabularyEntry} from '../../../src/model/VocabularyEntry'
import vocabularyService from '../../../src/services/vocabularyService'

jest.mock('../../../src/services/vocabularyService', () => jest.fn())

vocabularyService.mockImplementation(() => ({
  vocabulary: [new VocabularyEntry("a", "a1")]
}))

This will first mock the module with a simple spy and after all stuff is imported it sets the real implementation of the mock.

ksav
  • 20,015
  • 6
  • 46
  • 66
Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297
  • This seems to be a good approach! I tried this but it causes an error when the `Vocabulary` tries to to call `vocabularyService.vocabulary.map` because`vocabularyService.vocabulary` is undefined. I logged out the `vocabularyService` and it is a jest-mock-function. Maybe this is the problem? – Ria Jun 20 '17 at 12:07
  • Ah sorry, there was a bug in my code, `mockImplementation` needs to return a function not just the object. – Andreas Köberle Jun 20 '17 at 12:36
  • Not working for me :( please see https://stackoverflow.com/questions/45771844/mock-mockimplementation-not-working. – Janos Aug 19 '17 at 13:04
  • 6
    When I do this, I get `myService.mockImplementation is not a function`. – mcv Sep 02 '20 at 13:17
  • 8
    This doesn't work at all. Moving `jest.mock` to `beforeAll` gives the same error and using `mockImplementation` gives `TypeError: mockedModule.mockedFunction is not a function`. – thisismydesign Oct 19 '20 at 12:25
  • @thisismydesign Any luck in solving this issue? – Sangeeth Mukundan Jan 10 '21 at 05:25
  • 1
    Yes, I posted an answer: https://stackoverflow.com/a/64427443/2771889 – thisismydesign Jan 10 '21 at 11:06
53

If you are getting similar error when upgrading to newer Jest [19 to 21 in my case], you can try changing jest.mock to jest.doMock.

Found this here – https://github.com/facebook/jest/commit/6a8c7fb874790ded06f4790fdb33d8416a7284c8

Misha Reyzlin
  • 13,736
  • 4
  • 54
  • 63
9
jest.mock("../../../src/services/vocabularyService", () => {
  // eslint-disable-next-line global-require
  const VocabularyEntry = require("../../../src/model/VocabularyEntry");

  return {
    vocabulary: [new VocabularyEntry("a", "a1")]
  };
});

I think it should work with dynamic imports as well instead of require but didn't manage to make it work.

thisismydesign
  • 21,553
  • 9
  • 123
  • 126
5

When implementing a jest.fn() in a module, which was mocked with jest.mock, make sure you do the following two steps:

  1. The variable name should begin with mock.
  2. If you wrote something like coolFunction: mockCoolFunction, make sure to change it to coolFunction: (...args) => mockCoolFunction(...args). This way, Jest doesn’t need to know what mockCoolFunction is, as long as you haven’t run the function.

For further information, I recommend this blog post.

Marten
  • 645
  • 7
  • 21
  • Please look at this question facing same issue here : https://stackoverflow.com/questions/73977384/the-module-factory-of-jest-mock-is-not-allowed-to-reference-any-out-of-scope – user2028 Oct 07 '22 at 09:39
  • This is the solution that helped me! I had to change it to (arg1) => mockCoolFunction(arg1) in my case but that will vary depending on your assertions and how your function is called – LeaveTheCapital Dec 13 '22 at 20:56
1

For a project I worked on, I tried all the solutions listed here and none of them worked.

I was mocking the module like this:

import { myModuleFn } from 'myModule';

jest.mock('myModule', () => {
  return {
    __esModule: true,
    ...jest.requireActual('myModule'),
    myModuleFn: jest.fn(),
  };
});

Using Object.assign instead of spread operator fixed the error:

jest.mock('myModule', () => {
  return Object.assing({}, jest.requireActual('myModule'), {
    __esModule: true,
    myModuleFn: jest.fn(),
  })
});

I suspect it has to do with the jest or compiler configuration specific to the project.

David Ferreira
  • 1,233
  • 17
  • 24
0

In my case this issue started after I was upgrade my react-native project to v0.61 using react-native-git-upgrade.

After I have tried everything I could. I decide to clean the project and all my tests back to work.

# react-native-clean-project

However watch out when running the react-native-clean-project, it can wipe out all ios and android folder including native code, so just answer N when prompted. In my case I just selected wipe node_modules folder.

Cassio Seffrin
  • 7,293
  • 1
  • 54
  • 54