jest.mock doesn't mock the module imported in test file

Viewed 319

I'm trying to mock module generating uuid that is used inside the function that I test, and for some reason jest.mock fails to mock it.

file structure

- __test__
-- testFunc.test.ts
- uuidGenerator.ts
- testFunc.ts

./testFunc.ts

import uuidGenerator from "./uuidGenerator";

export const getUUID = () => {
  return uuidGenerator().generateUUID();
};

./uuidGenerator.ts

export default function uuidGenerator() {
  return { generateUUID: () => "generated-uuid" };
}

./__tests__/testFunc.test.ts

import { getUUID } from "../testFunc";

const testVal = "test-uuid";

jest.mock("../uuidGenerator", () =>
  jest.fn(() => ({
    generateUUID: () => testVal,
  }))
);

describe("test func", function () {
  it("should return expected", function () {
    expect(getUUID()).toBe(testVal);
  });
});

test output:

Error: expect(received).toBe(expected) // Object.is equality

Expected: "test-uuid"
Received: "generated-uuid"

console.log(uuidGenerator) from testFunc.ts returns:

    [Function: uuidGenerator]

Edit: I'm using jest 25.5 and here is the configuration file:

module.exports = {
  testRegex: "/__tests__/.*(\\.test.js|\\test.jsx|\\.test.ts|\\.test.tsx)$",
  testResultsProcessor: "./node_modules/jest-html-reporter",
  setupFilesAfterEnv: ["<rootDir>test-setup.js"],
  moduleFileExtensions: [
    "ts",
    "tsx",
    "ios.ts",
    "android.ts",
    "web.ts",
    "ios.tsx",
    "android.tsx",
    "web.tsx",
    "js",
    "json",
    "jsx",
    "web.js",
    "ios.js",
    "android.js",
    "ejs",
  ],
  snapshotSerializers: ["enzyme-to-json/serializer"],
  modulePaths: ["<rootDir>/packages", "<rootDir>/plugins", "<rootDir>/scripts"],
  modulePathIgnorePatterns: ["<rootDir>/xxx/"],
  collectCoverageFrom: ["packages/**/*.js", "plugins/**/*.js"],
  coveragePathIgnorePatterns: [
    "__tests__",
    "__mocks__",
    "node_modules",
    "test_helpers",
    "flow-types.js",
  ],
  transformIgnorePatterns: [
    "node_modules/(?!(react-native|react-native-webview|react-native-status-bar-height|react-router-native/)"
  ],
  transform: {
    "^.+\\.(js|ts|tsx)$": require.resolve("react-native/jest/preprocessor.js"),
    "^.+\\.ejs$": "<rootDir>/tools/ejs-transformer.js",
  },
  testEnvironment: "node",
  preset: "react-native",
  verbose: true,
  watchPlugins: [
    "jest-watch-typeahead/filename",
    "jest-watch-typeahead/testname",
  ],
};

Looks like the module is not getting mocked at all. Can anyone understand why is it happening?

1 Answers

Which version of Yarn are you using ? I just copy-pasted your code and run the test using Jest 26 and everything was working as expected.

Maybe you could try clearing the Jest cache folder : https://jestjs.io/docs/cli#--clearcache

Related