我正在使用 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" }
我可以透過將下面的程式碼新增至 package.json 來強制 jest 導入 commonjs axios 建置來修復此錯誤