NX Monorepo中React集成MSW+Jest测试遇模块语法错误
NX Monorepo React项目配置MSW + Jest测试报错解决
问题描述
在NX Monorepo的React项目中配置MSW与Jest测试,执行nx test my-app时触发语法错误:
Jest encountered an unexpected token /frontend/node_modules/msw/lib/node/index.d.ts:1 ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { PartialDeep } from 'type-fest'; SyntaxError: Cannot use import statement outside a module
未引入MSW的测试用例均可正常执行。
相关配置文件
jest.config.ts
export default { displayName: 'my-app', preset: '../../jest.preset.js', transform: { '^(?!.*\\.(js|jsx|ts|tsx|css|json)$)': '@nrwl/react/plugins/jest', '^.+\\.[tj]sx?$': ['babel-jest', { presets: ['@nrwl/react/babel'] }], }, moduleNameMapper: { '\\\\.svg$': '<rootDir>/src/__mocks__/svg.js', }, setupFiles: ["<rootDir>/jest.setup.ts"], moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'], coverageDirectory: '../../coverage/apps/my-app', setupFilesAfterEnv: ['@testing-library/jest-dom'], };
.babelrc
{ "presets": [ [ "@nrwl/react/babel", { "runtime": "automatic" } ] ], "plugins": [["styled-components", { "pure": true, "ssr": true }]], "env": { "test": { "plugins": ["@babel/plugin-transform-modules-commonjs"] } } }
package.json devDependencies
"devDependencies": { "@babel/plugin-transform-modules-commonjs": "^7.23.3", "@babel/preset-env": "^7.23.3", "@babel/preset-react": "^7.23.3", "@babel/preset-typescript": "^7.23.3", "@inrupt/jest-jsdom-polyfills": "^2.5.0", "@nrwl/cli": "14.4.2", "@nrwl/cypress": "14.4.2", "@nrwl/eslint-plugin-nx": "14.4.2", "@nrwl/jest": "14.4.2", "@nrwl/linter": "14.4.2", "@nrwl/nx-cloud": "latest", "@nrwl/react": "14.4.2", "@nrwl/web": "14.4.2", "@nrwl/workspace": "14.4.2", "@testing-library/jest-dom": "^5.16.4", "@testing-library/react": "^14.1.2", "@testing-library/user-event": "^14.4.3", "@types/jest": "^29.5.10", "babel-jest": "^29.7.0", "babel-plugin-styled-components": "1.10.7", "jest": "^29.7.0", "jest-environment-jsdom": "^29.7.0", "jest-watch-typeahead": "^1.1.0", "msw": "^2.0.8", "nx": "14.4.2", "ts-jest": "^29.1.1", "ts-node": "~10.8.0" }
修复步骤
1. 让Jest转译MSW包
修改jest.config.ts,添加transformIgnorePatterns配置,排除MSW及依赖包,让Babel处理它们:
export default { // 原有配置... transformIgnorePatterns: [ 'node_modules/(?!(msw|type-fest)/)', ], };
2. 优化Babel测试环境配置
确保.babelrc的test环境包含完整的预设,将ES模块转译为CommonJS:
{ // 原有配置... "env": { "test": { "presets": [ ["@babel/preset-env", { "targets": { "node": "current" } }], "@nrwl/react/babel" ], "plugins": ["@babel/plugin-transform-modules-commonjs", ["styled-components", { "pure": true, "ssr": true }]] } } }
3. 清除Jest缓存
执行命令清除缓存,避免旧配置干扰:
nx test my-app --clearCache
4. 重新运行测试
再次执行nx test my-app即可正常运行含MSW的测试用例。
内容的提问来源于stack exchange,提问作者AL Theri
相关产品推荐
相关产品推荐

