我试图模拟生成uuid的模块,这个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",
],
};
看起来这个模块根本没有被嘲笑过。有人能理解为什么会发生这种事吗?
发布于 2021-08-19 15:17:27
你用的是哪个版本的纱?我只需复制粘贴您的代码并使用Jest 26运行测试,一切都按预期进行。
也许您可以尝试清除Jest缓存文件夹:https://jestjs.io/docs/cli#--clearcache
https://stackoverflow.com/questions/68846859
复制相似问题