必要的利器--jest测试环境的搭建【vue3源码解析:一】

253 阅读1分钟

一. 什么是jest

如果有小伙伴还不知道jest的是话,最好的建议是动动发财的小手自行Google一下,手动狗头

二. 安装

1.首先创建一个文件:

mkdir vue-study

2.进入到vue-study中,执行命令生成 package.json 文件

npm init -y
  1. 安装所需的依赖
npm i @types/jest jest ts-jest typescript 
  1. 顺利的话在 package.json 会看到生成的依赖
"devDependencies": {
  "@types/jest": "^27.4.1",
  "jest": "^27.5.1",
  "ts-jest": "^27.1.3",
  "typescript": "^4.6.2"
},

三. 配置

  1. 打开package.json文件,将script下的test的值修改为jest
"scripts": {
  "test": "jest"
},
  1. 在根目录下创建 jest.config.js文件并添加配置
module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
}
  1. 同样在根目录下创建 tsconfig.json并添加配置
{
  "compilerOptions": {
    "strict": true,
    "moduleResolution": "node",
    "esModuleInterop": true,
    "target": "es2016",
    "module": "esnext",
    "noImplicitAny": false,
    "removeComments": true,
    "preserveConstEnums": true,
    "sourceMap": true,
    "downlevelIteration": true,
    "lib": [
      "es6",
      "DOM"
    ]
  }
}

四.编写测试用例

  1. 创建目录 src/compile-dom,进入到compile-dom中,并创建目录 __ test __ (两个下划线)

  2. 进入到 __ test __ 创建文件 index.spec.ts, 添加代码

import { compile } from '../index'

describe('compile', () => {
 it('should contain standard transforms', () => {
   const code = compile(`{{数值}}`)
   expect(code).toMatchSnapshot()
 })
})
  1. 回到compile-dom目录中,添加 index.ts文件
export function compile(template: string) {
  const.log('init:', template)
}
  1. 运行测试用例不出意外会在console.log中打印出 init: {{数值}},说明jest环境已经配置好了

1.png

小结:

在日常的开发中我们可能很少去写测试用例,但不得不说在写组件库,或者框架的时候,jest可以说是一把利器,用好它能带来很大的收益。