Service mocked with Jest causes "The module factory of jest.mock() is not allowed to reference any out-of-scope variables" error

Unit TestingReactjsBabeljsJestjs

Unit Testing Problem Overview


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.

Unit Testing Solutions


Solution 1 - Unit Testing

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

});

Solution 2 - Unit Testing

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.

Solution 3 - Unit Testing

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

Solution 4 - Unit Testing

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.

Solution 5 - Unit Testing

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRiaView Question on Stackoverflow
Solution 1 - Unit TestingmaxletouView Answer on Stackoverflow
Solution 2 - Unit TestingAndreas KöberleView Answer on Stackoverflow
Solution 3 - Unit TestingMisha ReyzlinView Answer on Stackoverflow
Solution 4 - Unit TestingthisismydesignView Answer on Stackoverflow
Solution 5 - Unit TestingCassio SeffrinView Answer on Stackoverflow