我做了一个模块级别的模拟,将一个 module.js 文件放在__mocks__
node_modules 旁边的文件夹中。(项目根级别)
node_modules/
__mocks__/module.js
然后在里面的module.js文件中__mocks__
我做:
const api = jest.genMockFromModule("module");
module.exports = api;
它工作正常(模拟完成),但是当我尝试在我的测试(module.someFunc)上更改“模块”的任何模拟函数实现时,它不会取代模拟实现:
import * as api from "module";
api.someFunc.mockImplementation(() => Promise.resolve([]);
// OR
api.someFunc = jest.fn().mockImplementation(() => Promise.resolve([]);
// OR
jest.onSpy(api, "someFunc").mockImplementation(() => Promise.resolve([]);
// Tryied with commonJS to
const api = require("module")
api.someFunc.mockImplementation(() => Promise.resolve([]);
// OR
api.someFunc = jest.fn().mockImplementation(() => Promise.resolve([]);
// OR
jest.onSpy(api, "someFunc").mockImplementation(() => Promise.resolve([]);
使用带有 ts-jest 的打字稿;
笑话配置:
module.exports = {
preset: "ts-jest/presets/js-with-babel",
globals: {
'ts-jest': {
diagnostics: false,
}
},
testPathIgnorePatterns: ["<rootDir>/node_modules/", "<rootDir>/src/__tests__/setup/"],
setupFilesAfterEnv: [
"react-testing-library/cleanup-after-each",
"jest-dom/extend-expect",
],
moduleNameMapper: {
"\\.(scss)$": "<rootDir>node_modules/jest-css-modules"
}
};