Search code examples
typescriptexpressjestjsts-jest

How to run jest on a typescript/expressjs app with typeRoots enabled on tsconfig.json


Well, I've got this project here, and it contains typescript and expressjs. My goal right now is building the tests, but when I run yarn test (which runs jest without any flags), I get this error:

PS C:\Users\joaov\Documents\gittin> yarn test
yarn run v1.22.10
$ jest
Error: Jest: Failed to parse the TypeScript config file C:\Users\joaov\Documents\gittin\jest.config.ts
  TSError: ⨯ Unable to compile TypeScript:
jest.config.ts:1:1 - error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.

1 module.exports = {
  ~~~~~~

    at readConfigFileAndSetRootDir (C:\Users\joaov\Documents\gittin\node_modules\jest-config\build\readConfigFileAndSetRootDir.js:118:13)
    at readConfig (C:\Users\joaov\Documents\gittin\node_modules\jest-config\build\index.js:227:18)
    at readConfigs (C:\Users\joaov\Documents\gittin\node_modules\jest-config\build\index.js:412:26)
    at runCLI (C:\Users\joaov\Documents\gittin\node_modules\@jest\core\build\cli\index.js:220:59)
    at Object.run (C:\Users\joaov\Documents\gittin\node_modules\jest-cli\build\cli\index.js:163:37)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

I was told that happens because in my tsconfig.json the property typeRoots is enabled. When I comment that line, the tests really work, but I'd like to know how to keep the typeRoots working along with jest, since I'll need that local type.

Just to be quicker, these are the tsconfig.json and jest.config.ts, respectively:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "outDir": "dist",
    "rootDir": "src",
    "removeComments": true,
    "strict": true,
    "strictPropertyInitialization": false,
    "typeRoots": ["./src/@types"],
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "exclude": [
    "src/**/*.spec.ts",
    "src/**/*.test.ts",
    "jest.config.ts",
    "ormconfig.js",
    "node_modules"
  ]
}
module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
};

Solution

  • found out that I just needed to add ./node_modules/@types to typeRoots option in the tsconfig file.