Accepted answer

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.


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.


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.


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 –


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


Related Query

More Query from same tag