nx monorepo. Jest testing with msw. Error "Cannot use import statement outside a module" in setupServer import

325 Views Asked by At

I use nx monorepo with react and try setup jest testing with msw (according to documentation https://redux.js.org/usage/writing-tests#example-app-code)

Run test nx test my-app and get error below. All other tests without msw work correct

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"]
    }
  }
}

devdependencies in package.json

"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

There are 1 best solutions below

1
On

In your package.json make sure you have the line "type": "module"

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