【问题标题】:jest.mock doesn't mock the module imported in test filejest.mock 不模拟在测试文件中导入的模块
【发布时间】:2021-10-21 02:29:49
【问题描述】:

我正在尝试模拟生成在我测试的函数中使用的 uuid 的模块,并且由于某种原因 jest.mock 无法模拟它。

文件结构

- __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);
  });
});

测试输出:

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

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

console.log(uuidGenerator) 来自 testFunc.ts 返回:

    [Function: uuidGenerator]

编辑:我使用的是 jest 25.5,这是配置文件:

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",
  ],
};

看起来该模块根本没有被嘲笑。谁能明白为什么会这样?

【问题讨论】:

    标签: javascript typescript unit-testing jestjs


    【解决方案1】:

    您使用的是哪个版本的 Yarn?我只是复制粘贴了您的代码并使用 Jest 26 运行测试,一切都按预期工作。

    也许您可以尝试清除 Jest 缓存文件夹:https://jestjs.io/docs/cli#--clearcache

    【讨论】:

    • 很遗憾,清理缓存不起作用。我正在使用 yarn 1.12.10 和 jest 25.5(我已经用 jest 配置更新了原始问题)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多