TS + Webpack 整合 Jest

  1. 安装 Jest 和相关依赖

    首先,安装 Jest 和 TypeScript 的 Jest 预处理器ts-jest以及类型定义文件。

    npm install --save-dev jest ts-jest @types/jest
    
  2. 初始化 Jest 配置

    使用ts-jest初始化 Jest 配置文件。

    npx ts-jest config:init
    

    这会生成一个基本的 Jest 配置文件jest.config.js。如果没有生成,手动创建该文件并添加以下内容:

    module.exports = {
      preset: 'ts-jest',
      testEnvironment: 'node',
      moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
      transform: {
        '^.+\\.(ts|tsx)$': 'ts-jest',
      },
      testMatch: ['**/?(*.)+(spec|test).[tj]s?(x)'],
    };
    
  3. 配置 TypeScript

    确保你的tsconfig.json文件包含jest的类型定义:

    {
      "compilerOptions": {
        "types": ["jest"]
      }
    }
    
  4. 编写测试

    在你的项目中编写测试文件,通常放在__tests__目录或者与源文件同名但以.test.ts.spec.ts结尾。例如,在src目录下创建example.test.ts

    // src/example.test.ts
    import { myFunction } from './example';
    
    test('myFunction should return correct value', () => {
      expect(myFunction(1)).toBe(2);
    });
    

    注意,要将测试文件或文件所在目录放在tsconfig.json中指定的compilerOptions.rootDir下,不然会报Unable to process '...__tests__\utils.test.ts'之类的错误。

  5. 更新 npm 脚本

    package.json中添加一个脚本来运行 Jest:

    {
      "scripts": {
        "test": "jest"
      }
    }
    
  6. 配置 ESLint

    如果项目中使用了 ESLint,可能会提示 test 等函数未定义(no-undef),将下面的overrides配置加到.eslintrc.js中可以解决:

    {
       "overrides": [
           {
               "files": ["**/?(*.)+(spec|test).[tj]s?(x)"],
               "env": {
                   "jest": true
               }
           }
       ]
    }
    
  7. 运行测试

    运行以下命令来执行测试:

    npm test
    

参考:ChatGPT、javascript - eslint throws `no-undef` errors when linting Jest test files - Stack Overflow

posted @ 2024-05-30 22:37  Higurashi-kagome  阅读(12)  评论(0编辑  收藏  举报