Jest 配置module

149 阅读2分钟

Jest目前在很多前端项目中使用,该测试框架能快速的让我们测试接口,及时反馈接口的可用性。
Jest中文官网
今天我们来使用package.json中的type属性,配置module。 因为该方式是Jest的实验性支持,最好Jest是最新版本,本文使用Jest 29.4.*以上版本,使用27.*版本时遇到无法解析ts的问题,升级后解决。

第一步:创建项目

在你需要创建项目的位置,先创建工程目录,在终端进入工程目录,使用npm init命令初始化package.json文件,初始化生成的文件如下:

    { 
        "name": "my-project", 
        "version": "1.0.0", 
        "description": "this is my project",
        "main": "app.js",
        "scripts": { 
            "test": "echo \"Error: no test specified\" && exit 1" 
        }, 
        "author": "xxx", 
        "license": "ISC" 
    }

第二步 配置module

package.json中增加type属性,属性值是module,将test值改为jest,修改后运行yarn test时会运行此命令执行jest。module配置,会将.js或无扩展的文件视为ES模块处理。

    { 
        "name": "my-project", 
        "version": "1.0.0", 
        "description": "this is my project",
        "main": "app.js",
        "type": "module",
        "scripts": { 
            "test": "jest" 
        }, 
        "author": "xxx", 
        "license": "ISC" 
    }

第三步 添加Jest、Babel、Typescript

我使用了yarn来添加,因为是开发环境使用,所以添加到开发时使用插件。大家也可以用npm或pnpm来安装Jest

yarn add jest ts-jest @types/jest babel-jest @babel/core @babel/preset-env typescript -D

第四步 添加配置文件

  1. 在根目录下创建babel.config.js,支持当前node版本
module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        targets: {
          node: 'current',
        },
      },
    ],
  ],
};
  1. 使用命令初始化Jest基础配置,jest init在根目录下会出现jest的配置文件,以下是我的jest简单配置
import type { Config } from '@jest/types';
const config:Config.InitialOptions = {
  preset: 'ts-jest',
  verbose: true,
  moduleFileExtensions: ['ts', 'tsx', 'js'],
  testEnvironment: 'node',
  testRegex: "(/__tests__/.*|(\.|/)(test))\.(ts?)$"
}

module.exports = config;

第五步 添加测试用例

在根目录下创建__test__目录,创建index.test.ts测试用例,一个简单的测试用例如下:

const sum =(x:number,y:number)=>x+y

describe('sum', function() {
  it('should sum', function() {
    expect(sum(1,2)).toBe(3)
  })
})

然后运行yarn test,会执行package.json中test命令,如果运行成功其结果:

好了,以上是package.json中type属性值是module,Jest的配置方式