在另一个函数导入我的测试模块后,我无法更改另一个函数的模拟行为。 “ functionUsingMockFunction”将调用“ mockFunction”,并应使用其返回值进行处理。但是,按以下方式设置测试时,测试失败,因为“ mockFunction”返回未定义。此外,我可以在任何需要的地方更改npm依赖项的嘲笑实现,但是我不能轻易模仿在自己的模块中导出的函数。 beforeEach中的“ jest.resetModules()”也不起作用。
jest.mock("../moduleToMock");
const { mockFunction } = require("../moduleToMock");
// if mockFunction.mockImplementation was defined here, it would work
const { functionUsingMockFunction } = require("./someModule");
...
let result;
beforeEach(async () => {
mockFunction.mockImplementation(() => ({
// return some object
}));
// if functionUsingMockFunction was imported now, it would also work
result = await functionUsingMockFunction();
});
it("does something", () => {
expect(result).toEqual("some result");
});
});
此设置可在我的其他项目中使用,因此我认为这可能与我的jest / babel配置有关,但是我没有发现任何重大差异。 我正在使用节点10.15.1。 我的开发依赖项:
"devDependencies": {
"@babel/core": "^7.0.0",
"@babel/plugin-proposal-class-properties": "^7.0.0",
"@babel/preset-env": "^7.4.4",
"@babel/preset-react": "^7.0.0",
"babel-core": "7.0.0-bridge.0",
"babel-eslint": "^10.0.0",
"babel-jest": "24.8.0",
"babel-loader": "^8.0.0",
"clean-webpack-plugin": "^1.0.0",
"concurrently": "^4.0.0",
"css-loader": "^2.0.0",
"enzyme": "^3.9.0",
"enzyme-adapter-react-16": "^1.12.1",
"eslint": "^5.16.0",
"eslint-config-airbnb": "^17.0.0",
"eslint-plugin-import": "^2.11.0",
"eslint-plugin-jest": "^22.5.1",
"eslint-plugin-jsx-a11y": "^6.0.3",
"eslint-plugin-react": "^7.7.0",
"file-loader": "^3.0.0",
"html-webpack-plugin": "^3.2.0",
"jest": "24.8.0",
"nodemon": "^1.17.3",
"react-test-renderer": "^16.8.6",
"style-loader": "^0.23.0",
"url-loader": "^1.0.1",
"webpack": "^4.5.0",
"webpack-cli": "^3.0.8",
"webpack-dev-server": "^3.1.3"
}
配置:
// babel.config.js
module.exports = {
presets: ["@babel/preset-env", "@babel/preset-react"],
plugins: ["@babel/plugin-proposal-class-properties"]
};
// jest.config.js
module.exports = {
setupFilesAfterEnv: ["./test/setupTests.js"],
moduleNameMapper: {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$":
"<rootDir>/__mocks__/fileMock.js",
"\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
}
};
// setupTests.js
import { configure } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import "babel-polyfill";
configure({ adapter: new Adapter() });