nx monorepo. Jest测试与msw.错误“无法使用导入语句外的模块”在setupServer导入

ecfsfe2w  于 2024-01-04  发布在  Jest
关注(0)|答案(1)|浏览(262)

我使用nx monorepo和react,并尝试使用msw设置jest测试(根据文档https://redux.js.org/usage/writing-tests#example-app-code)
运行测试nx test my-app并得到下面的错误。所有其他没有msw的测试都正常工作

  1. Jest encountered an unexpected token
  2. /frontend/node_modules/msw/lib/node/index.d.ts:1
  3. ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { PartialDeep } from 'type-fest';
  4. SyntaxError: Cannot use import statement outside a module

字符串
Error
jest.config.ts

  1. export default {
  2. displayName: 'my-app',
  3. preset: '../../jest.preset.js',
  4. transform: {
  5. '^(?!.*\\.(js|jsx|ts|tsx|css|json)$)': '@nrwl/react/plugins/jest',
  6. '^.+\\.[tj]sx?$': ['babel-jest', { presets: ['@nrwl/react/babel'] }],
  7. },
  8. moduleNameMapper: {
  9. '\\.svg$': '<rootDir>/src/__mocks__/svg.js',
  10. },
  11. setupFiles: ["<rootDir>/jest.setup.ts"],
  12. moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
  13. coverageDirectory: '../../coverage/apps/my-app',
  14. setupFilesAfterEnv: ['@testing-library/jest-dom'],
  15. };


.babelrc

  1. {
  2. "presets": [
  3. [
  4. "@nrwl/react/babel",
  5. {
  6. "runtime": "automatic"
  7. }
  8. ]
  9. ],
  10. "plugins": [["styled-components", { "pure": true, "ssr": true }]],
  11. "env": {
  12. "test": {
  13. "plugins": ["@babel/plugin-transform-modules-commonjs"]
  14. }
  15. }
  16. }


package.json中的devdependencies

  1. "devDependencies": {
  2. "@babel/plugin-transform-modules-commonjs": "^7.23.3",
  3. "@babel/preset-env": "^7.23.3",
  4. "@babel/preset-react": "^7.23.3",
  5. "@babel/preset-typescript": "^7.23.3",
  6. "@inrupt/jest-jsdom-polyfills": "^2.5.0",
  7. "@nrwl/cli": "14.4.2",
  8. "@nrwl/cypress": "14.4.2",
  9. "@nrwl/eslint-plugin-nx": "14.4.2",
  10. "@nrwl/jest": "14.4.2",
  11. "@nrwl/linter": "14.4.2",
  12. "@nrwl/nx-cloud": "latest",
  13. "@nrwl/react": "14.4.2",
  14. "@nrwl/web": "14.4.2",
  15. "@nrwl/workspace": "14.4.2",
  16. "@testing-library/jest-dom": "^5.16.4",
  17. "@testing-library/react": "^14.1.2",
  18. "@testing-library/user-event": "^14.4.3",
  19. "@types/jest": "^29.5.10",
  20. "babel-jest": "^29.7.0",
  21. "babel-plugin-styled-components": "1.10.7",
  22. "jest": "^29.7.0",
  23. "jest-environment-jsdom": "^29.7.0",
  24. "jest-watch-typeahead": "^1.1.0",
  25. "msw": "^2.0.8",
  26. "nx": "14.4.2",
  27. "ts-jest": "^29.1.1",
  28. "ts-node": "~10.8.0",

af7jpaap

af7jpaap1#

在你的package.json中,确保你有"type": "module"

  1. {
  2. "name": "Some Name",
  3. "version": "1.0.0",
  4. "type": "module",
  5. // ...
  6. }

字符串

相关问题