Jest 是当下最主流的前端测试框架
首先初始化ts环境
image.png

yarn add typescript --dev
npx tsc --init

第二步:安装ts下的jest
yarn add jest @types/jest --dev

第三步:新建tests文件夹
tests/index.spec.ts

it('init',()=>{
    expect(true).toBe(true)
})

此处记住要在tsconfig.json里面修改配置
"types": ["jest"],

第四步
package.json添加

 "scripts": {
    "test":"jest"
  },

执行npm run test
得到
image.png

接下来处理导入模块的问题
index.ts

export function add (a,b){
    return a+b
}

index.spec.ts

import { add } from "../index"
it('init',()=>{
    expect(add(2,3)).toBe(5)
})

执行npm run test报错
image.png

打开https://www.jestjs.cn/docs/getting-started
配置 Babel

npm install --save-dev babel-jest @babel/core @babel/preset-env

在项目的根目录下创建 babel.config.js ,通过配置 Babel 使其能够兼容当前的 Node 版本。

babel.config.js
module.exports = {
  presets: [['@babel/preset-env', {targets: {node: 'current'}}]],
};

使用 Typescript
通过 babel 来支持 Typescript
通过 Babel,Jest 能够支持 Typescript。首先要确保你遵循了上述 使用 Babel 指引。接下来安装 @babel/preset-typescript 插件:

npm install --save-dev @babel/preset-typescript
babel.config.js
module.exports = {
  presets: [
    ['@babel/preset-env', {targets: {node: 'current'}}],
    '@babel/preset-typescript',
  ],
};

最后执行npm run test
image.png

初步完成在ts环境下的jest单测


ohoherror
21 声望1 粉丝