首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >jest.mock不模拟测试文件中导入的模块

jest.mock不模拟测试文件中导入的模块
EN

Stack Overflow用户
提问于 2021-08-19 11:19:08
回答 1查看 389关注 0票数 1

我试图模拟生成uuid的模块,这个uuid在我测试的函数中使用,但由于某种原因,jest.mock没有对它进行模拟。

文件结构

代码语言:javascript
运行
复制
- __test__
-- testFunc.test.ts
- uuidGenerator.ts
- testFunc.ts

./testFunc.ts

代码语言:javascript
运行
复制
import uuidGenerator from "./uuidGenerator";

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

./uuidGenerator.ts

代码语言:javascript
运行
复制
export default function uuidGenerator() {
  return { generateUUID: () => "generated-uuid" };
}

./__tests__/testFunc.test.ts

代码语言:javascript
运行
复制
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);
  });
});

测试输出:

代码语言:javascript
运行
复制
Error: expect(received).toBe(expected) // Object.is equality

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

console.log(uuidGenerator)从testFunc.ts返回:

代码语言:javascript
运行
复制
    [Function: uuidGenerator]

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

代码语言:javascript
运行
复制
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",
  ],
};

看起来这个模块根本没有被嘲笑过。有人能理解为什么会发生这种事吗?

EN

回答 1

Stack Overflow用户

发布于 2021-08-19 15:17:27

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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68846859

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档