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

ecfsfe2w  于 12个月前  发布在  Jest
关注(0)|答案(1)|浏览(216)

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

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

字符串
Error
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",

af7jpaap

af7jpaap1#

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

{
  "name": "Some Name",
  "version": "1.0.0",
  "type": "module",
  // ...
}

字符串

相关问题