我正在使用 React 和 Typescript。
在我的测试文件中,我尝试渲染一个组件
test("Render Header", () => {
render(<Header />);
});
标头组件正在使用 actions.tsx 中的操作创建器
import { loadRepo } from "../../redux/actions";
dispatch(loadRepo());
loadRepo 是使用 axios 的异步操作创建器。我的测试抛出错误,因为我在 actions.tsx 中导入了 axios。错误如下:无法在模块外部使用 import 语句。
我尝试设置 babel 和 jest 配置。这是我所拥有的。
babel.config.js
module.exports = {
presets: [["@babel/preset-env", { targets: { node: "current" } }], "@babel/preset-react", "@babel/preset-typescript"],
plugins: [],
};
jest.config.js
module.exports = {
setupFilesAfterEnv: ["@testing-library/jest-dom/extend-expect"],
moduleNameMapper: {
"\\.(css|less|scss|sass)$": "identity-obj-proxy",
},
transform: {
"^.+\\.(js|jsx|ts|tsx)$": "babel-jest",
},
};
package.json
"dependencies": {
"@testing-library/user-event": "^13.5.0",
"@types/node": "^16.18.23",
"@types/react": "^18.0.35",
"@types/react-dom": "^18.0.11",
"axios": "^1.3.5",
"bootstrap": "^5.2.3",
"react": "^18.2.0",
"react-bootstrap": "^2.7.3",
"react-dom": "^18.2.0",
"react-redux": "^8.0.5",
"react-scripts": "5.0.1",
"redux": "^4.2.1",
"redux-thunk": "^2.4.2",
"typescript": "^4.9.5",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"devDependencies": {
"@babel/core": "^7.21.4",
"@babel/preset-env": "^7.21.4",
"@babel/preset-react": "^7.18.6",
"@babel/preset-typescript": "^7.21.4",
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^14.0.0",
"babel-jest": "^29.5.0",
"jest": "^27.5.1"
} Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
我可以通过将下面的代码添加到 package.json 来强制 jest 导入 commonjs axios 构建来修复此错误
"jest": { "moduleNameMapper": { "axios": "axios/dist/node/axios.cjs" } },