In Typescript testing, you may need to check ts types, and @babel/preset- Typescript doesn’t work for you, so use TS-Jest for Typescript support.

A detailed comparison of TS-Jest and Babel can be seen in babel7-OR-TS.

The following describes how to test the React project using TS-Jest. Ts-jest is available in the official documentation.

The installation

yarn add -D jest ts-jest jest-enzyme enzyme enzyme-adapter-react-16 @types/enzyme @types/jest
Copy the code

configuration

  • Jest. Config. Ts configuration
import {Config} from '@jest/types'

export default {
  preset: 'ts-jest'.clearMocks: true.coverageDirectory: "coverage".testEnvironment: "jsdom".moduleFileExtensions: ['ts'.'js'.'json'.'tsx'].moduleDirectories: ['node_modules'.'src'].moduleNameMapper: {
    '^ @ / (. *) $': '<rootDir>/src/$1'
  },
  setupFiles: ['./test/setup.js'].// Introduce the jest-enzyme extension assertion support
  setupFilesAfterEnv: ['./node_modules/jest-enzyme/lib/index.js'].globals: {
    'ts-jest': {
      // Specify the tsconfig configuration used by ts-jest
      tsconfig: 'tsconfig.test.json'}}}as Config.InitialOptions;
Copy the code
  • Tsconfig. Test. Config configuration

JSX support is required

{
  "compilerOptions": {
    "target": "ES5",
    "types": ["jest", "jest-enzyme"],
    "allowJs": true,
    "skipLibCheck": false,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "jsx": "react"
  }
}
Copy the code

conclusion

With this configuration, you take advantage of THE compilation capabilities of TSC directly, without the need for Babel. You can configure JSX to support React. Much closer to typescript than Babel.