[英]jest.mock doesn't mock the module imported in test file
我正在嘗試模擬生成 uuid 的模塊,該 uuid 在我測試的 function 內部使用,但由於某種原因 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);
});
});
測試 output:
Error: expect(received).toBe(expected) // Object.is equality
Expected: "test-uuid"
Received: "generated-uuid"
來自 testFunc.ts 的console.log(uuidGenerator)
返回:
[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",
],
};
看起來該模塊根本沒有被嘲笑。 誰能理解為什么會這樣?
您使用的是哪個版本的 Yarn? 我只是復制粘貼您的代碼並使用 Jest 26 運行測試,一切都按預期工作。
也許你可以嘗試清除 Jest 緩存文件夾: https://jestjs.io/docs/cli#--clearcache
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.