#app works, but jest fails to import modules

5 messages · Page 1 of 1 (latest)

surreal shore
#

I have problems to import the npm package 'serialize-error' when I am using ts-jest. Everything works as expected when I just run my app. But when I try to run tests, jest complains

    SyntaxError: Cannot use import statement outside a module

      1 | import { maxObjectDepth } from "../defaults"
      2 | import { ZodError, ZodIssue } from "zod"
    > 3 | import { serializeError } from "serialize-error"
        | ^
      4 |
      5 | type errorSerialized = {
      6 |   statusCode: number

I was trying to follow the instructions on the jest homepage regarding typescript but with no avail. I am afraid I am a wee bit out of my depths here. it is my first typescript project and I still not fully unterstand the link between the different ECMAscripts and modules. Currently running with the following typescript and jest config:

  • "node": "18.16.0"
  • "ts-jest": "^29.1.0",
  • "typescript": "^5.0.4",

tsconfig:

{
  "compilerOptions": {
    "lib": [
      "ES2022"
    ],
    "module": "es2022",
    "target": "es2022",
    "strict": true,
    "exactOptionalPropertyTypes": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "moduleResolution": "Node",
    "outDir": "build",
    "sourceMap": true
  },
  "exclude": [
    "node_modules",
    "**/__tests__/*",
    "**/integration_tests/*",
    "**/*.test.ts",
  ]
}

jest.config.ts:

import type { JestConfigWithTsJest } from "ts-jest"

const jestConfig: JestConfigWithTsJest = {
  // [...]
  moduleNameMapper: {
    "^(\\.{1,2}/.*)\\.js$": "$1",
  },
  transform: {
    // '^.+\\.[tj]sx?$' to process js/ts with `ts-jest`
    // '^.+\\.m?[tj]sx?$' to process js/ts/mjs/mts with `ts-jest`
    "^.+\\.ts?$": [
      "ts-jest",
      {
        useESM: true,
      },
    ],
  },
  testTimeout: 10000,
}

export default jestConfig

I tried some ignorepatterns as well, with no success. Thankful for any help and ideas.

lime jackal
#

In my experience such errors are due to legacy reasons in Jest. Is there any chance you could use a different test runner, like Vitest?

surreal shore
#

I will give it a try. My tests are actually quiet simple, so a migration might be not too tricky. Thank you

lime jackal
#

Afaik Vitest was designed to be a drop-in replacement, so it should be fine, probably. 🙂

surreal shore
#

It indeed was. literally just swapped packages, config and run command. And it soo much quicker and mostly important the imports are working now. Thank you a lot. 🙂