为 react typescript 项目设置 ts-jest

Posted

技术标签:

【中文标题】为 react typescript 项目设置 ts-jest【英文标题】:setting up ts-jest for react typescript project 【发布时间】:2018-12-11 09:48:27 【问题描述】:

我正在尝试为用 typescript 编写的 react 项目设置测试环境。我之前已经为 react 做过,但使用的是 ES6。

以下是我的 package.json 的相关部分的外观 -

 "scripts": 
    "test": "NODE_ENV=test jest",
    "build": "webpack --mode production",
    "start": "webpack-dev-server --open --mode development"
  ,
  "jest": 
    "moduleNameMapper": 
      "\\.(css)$": "jest-css-modules"
    ,
    "transform": 
      "\\.(ts|tsx)$": "ts-jest"
    ,
    "testRegex": ".test.(ts|tsx?)$",
    "moduleFileExensions": ["ts", "tsx", "js", "jsx", "json", "node"]
  ,

我要提一下,我是指望ts transpiler,根本没有配置babel。

以下是我包含的依赖项-

"dependencies": 
    "@types/jest": "^23.1.4",
    "@types/react": "^16.4.5",
    "@types/react-dom": "^16.0.6",
    "@types/react-redux": "^6.0.3",
    "@types/redux": "^3.6.0",
    "deep-freeze": "0.0.1",
    "jest": "^23.2.0",
    "jest-css-modules": "^1.1.0",
    "react-redux": "^5.0.7",
    "redux": "^4.0.0",
    "ts-jest": "^23.0.0",
    "webpack": "^4.12.2"
  ,
  "devDependencies": 
    "awesome-typescript-loader": "^5.2.0",
    "css-loader": "^0.28.11",
    "html-loader": "^0.5.5",
    "html-webpack-plugin": "^3.2.0",
    "prop-types": "^15.6.2",
    "react": "^16.4.1",
    "react-dom": "^16.4.1",
    "style-loader": "^0.21.0",
    "typescript": "^2.9.2",
    "typings-for-css-modules-loader": "^1.7.0",
    "url-loader": "^1.0.1",
    "webpack-cli": "^3.0.8",
    "webpack-dev-server": "^3.1.4"
  

我在运行npm run test 时无法理解以下错误,因为我已经安装并在转换中指定了 ts-jest -

Validation Error:

  Module ts-jest in the transform option was not found.
         <rootDir> is: /Users/rahul/ot/Lab/webpack-playlist

以下是 tsconfig.json 的样子


  "compilerOptions": 
    "jsx": "react",
    "noImplicitAny": true,
    "sourceMap": true,
    "target": "es5"
  

不确定如何解决上述错误。

我也尝试在 tsconfig.json 中配置 ts-jest,如下所示,但仍然报同样的错误 -

// tsconfig.json
    "jest": 
        "globals": 
          "ts-jest": 
            "tsConfigFile": "tsconfig.jest.json"
          
        
      


// tsconfig.jest.json

  "extends": "./tsconfig",
  "compilerOptions": 
    "module": "commonjs"
  

【问题讨论】:

【参考方案1】:

看这个,和我这里的设置没有什么不同:

https://github.com/jasonraimondi/typescript-react-starter

您的 jest 配置存在细微差别。以下是我的jest.config.js 文件的内容。

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

我有一篇关于 testing a Typescript React App using ts-jest without "create-react-app" 的帖子,希望对您有所帮助。

【讨论】:

【参考方案2】:

这是在 TypeScript React 项目中使用 Jest 的示例设置。我自己创建的,希望对您有所帮助:

jest.config.js

const defaults = require('jest-config');

module.exports = 
  bail: true,
  moduleFileExtensions: [...defaults.moduleFileExtensions, 'ts', 'tsx'],
  roots: ['src'],
  testMatch: ['<rootDir>/src/**/?(*.)test.ts,tsx'],
  transform: 
    '^.+\\.tsx?$': 'ts-jest',
  ,
  verbose: true,
;

package.json


  "dependencies": 
    "@types/react": "16.7.18",
    "@types/react-dom": "16.0.11",
    "react": "16.7.0",
    "react-dom": "16.7.0"
  ,
  "devDependencies": 
    "jest": "23.6.0",
    "ts-jest": "23.10.5"
  ,
  "scripts": 
    "test": "jest"
  ,
  "version": "0.0.0"

src/Welcome.tsx

import * as React from 'react';

interface WelcomeProps 
  name: string,


const Welcome: React.FunctionComponent<WelcomeProps> = (props: WelcomeProps) => 
  return <h1>Hello, props.name</h1>;
;

export default Welcome;

src/Welcome.test.tsx

import React from 'react';
import ReactDOM from 'react-dom';

import Welcome from './Welcome';

it('renders without crashing', () => 
  const div = document.createElement('div');
  ReactDOM.render(<Welcome name="John Doe"/>, div);
  ReactDOM.unmountComponentAtNode(div);
);

【讨论】:

【参考方案3】:

这是唯一对我有用的配置。这是我的规格:


  "name": "project",
  "version": "1.0.0",
  "description": "project",
  "jest": 
    "modulePathIgnorePatterns": [
      "dist/"
    ],
    "snapshotSerializers": [
      "enzyme-to-json/serializer"
    ],
    "moduleNameMapper": 
      "^.+\\.(css|less|scss)$": "identity-obj-proxy"
    ,
    "setupFilesAfterEnv": [
      "./setupTests.ts"
    ],
    "coverageReporters": [
      "text",
      "lcov"
    ],
    "coverageDirectory": ".",
    "transform": 
      ".(js|jsx)": "babel-jest",
      ".(ts|tsx)": "ts-jest"
    
  ,
  "peerDependencies": 
    "react": "^16.12.0",
    "react-dom": "^16.12.0"
  ,
  "devDependencies": 
    "@types/enzyme": "^3.10.5",
    "@types/enzyme-adapter-react-16": "^1.0.6",
    "@types/jest": "^26.0.4",
    "babel-preset-env": "^1.7.0",
    "babel-preset-react": "^6.24.1",
    "enzyme-adapter-react-16": "^1.12.1",
    "ts-jest": "^26.1.0",
    "typescript": "~3.9.5"
  ,
  "scripts": 
    "tsc": "tsc --build tsconfig.json",
    "watch": "tsc --watch",
    "test": "jest",
    "test-coverage": "jest --coverage"
  

setupTests.ts:

import * as Enzyme from 'enzyme';
import * as Adapter from 'enzyme-adapter-react-16';

Enzyme.configure( adapter: new Adapter() );

最后是我的 tsconfig.json:


  "compileOnSave": false,
  "compilerOptions": 
    "allowJs": true,
    "declaration": true,
    "declarationMap": true,
    "jsx": "react",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "skipLibCheck": true,
    "noImplicitAny": true,
    "target": "es5",
    "outDir": "./dist",
    "declarationDir": "./dist",
    "lib": ["es2016", "dom"]
  ,
  "include": ["./src/index.ts"]

【讨论】:

【参考方案4】:

我有同样的错误,并通过在终端中运行以下命令来修复它: 通过 npm: 1.“npm i -D jest typescript” 2.“npm i -D ts-jest @types/jest” 3.“npx ts-jest 配置:init” 4. "npm t or npx jest"

通过纱线: 1.“纱线添加--dev jest typescript” 2.“纱线添加--dev ts-jest @types/jest” 3.“纱线 ts-jest 配置:init” 4.“纱线测试或纱线笑话”

我使用的是 ubuntu 18.04.3 LTS。

【讨论】:

【参考方案5】:

根据ts-jest 的文档,您应该设置globals.tsConfig,但它必须是globals.tsconfig。例如:

globals: 
    'ts-jest': 
      // ts-jest configuration goes here
      // https://huafu.github.io/ts-jest/user/config/#ts-jest-options
      // specify tsconfig.json to be used by ts-jest
      tsconfig: '<rootDir>/test/tsconfig.test.json',
    ,
  ,

tsconfig 为我工作,tsConfig 没有。

来源:https://dev.to/ushakovmaksim/comment/1bc8j

【讨论】:

以上是关于为 react typescript 项目设置 ts-jest的主要内容,如果未能解决你的问题,请参考以下文章

Typescript 和 React:使用 React.Component 和条件类型化道具时类型推断失败

如何使用 ESLint 检查 React/Typescript 项目中的 prop 错误?

Jest 遇到了意外的令牌(React、Typescript、Babel、Jest 和 Webpack 设置)

如何在 Typescript 中将具有动态键的对象设置为 React 状态

如何使用 Typescript 和 useState 将类型对象设置为 React 的初始值?

typescript+reactjs+requirejs:如何将 react-dom 导入 typescript