eversor
eversor

Reputation: 3073

Using TypeScript with Jest not catching syntax errors

When compiling typescript back to js, you can specify the option --alwaysStrict which:

Parse in strict mode and emit "use strict" for each source file

So, if you are missing a compulsory parameter in a function, it gets caught by this strict mode.

We are using ts-jest so we can use Jest to test our Typescript code. The problem we face is that we have not found a way to mimic the strict parsing behaviour.

This is really annoying because all the test seem to pass, but from time to time there is a syntactic mistake that slips through the cracks and we only notice when we are creating the production build (where we set the --alwaysStrict)

In our jest.config.js we have:

module.exports = {
  roots: ["<rootDir>/src"],
  transform: {
    "^.+\\.tsx?$": "ts-jest"
  },
  testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$",
  moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
  "testEnvironment": "node"
};```

Upvotes: 5

Views: 2460

Answers (2)

Brian Adams
Brian Adams

Reputation: 45780

ts-jest uses the tsconfig.json from your project by default.

(Note: if you want a separate config file for your tests you can configure ts-jest to use a different config file)

You can set alwaysStrict in the compilerOptions section of the config file and ts-jest use that flag when compiling your TypeScript.

Upvotes: 3

smac89
smac89

Reputation: 43078

The only configuration option that enabled me to start seeing compiler errors when running tests is the following:

jest.config.ts:

{
   // ...
   transform: {
    // '^.+\\.[tj]sx?$' to process js/ts with `ts-jest`
    // '^.+\\.m?[tj]sx?$' to process js/ts/mjs/mts with `ts-jest`
    '^.+\\.tsx?$': [
      'ts-jest',
      {
        tsconfig: 'tests/tsconfig.json',
        diagnostics: {
          warnOnly: true, // <- This is the key
        },
      },
    ],
  },
}

Using any configuration which requires a custom tsconfig.json for testing, without specifying: diagnostics: { warnOnly: true }, will simply lead to jest silently failing tests without giving us even a clue as to what is happening. Not even simply diagnostics: true will work.

Even with the above option, you may or may not see those diagnostics warnings if you have enabled cache in jest config. Some solutions for this:

  1. Disable cache in jest config by setting the cache key to false.
  2. Clear jest cache before running your test by first doing jest --clearCache.

See also the exclude option which allows you to disable error-reporting for all non-test files.

Upvotes: 0

Related Questions