web前端实用知识&技巧

vitest单元测试简单分享(一)

2023-02-25  本文已影响0人  意随风起

先上源码:demo

文件路径:在项目根目录/vue3/my-vue-app文件夹下

一、项目搭建
安装vite和vue,使用 npm 或者 yarn、pnmp都行,终端命令如下:

# npm 6.x
npm create vite@latest my-vue-app --template vue

# npm 7+, extra double-dash is needed:
npm create vite@latest my-vue-app -- --template vue

# yarn
yarn create vite my-vue-app --template vue

# pnpm
pnpm create vite my-vue-app --template vue

二、Vitest、jsdom、 coverage安装
使用 npm 或者 yarn、pnmp都行,终端命令如下:

# npm
npm install -D vitest jsdom @vitest/coverage-c8

# yarn
yarn add -D vitest jsdom @vitest/coverage-c8

# pnpm
pnpm add -D vitest jsdom @vitest/coverage-c8

提示:Vitest 需要 Vite >=v3.0.0 和 Node >=v14

三、 修改项目根目录下的vite.config.js的配置文件,增加:

test: { include: ["tests/*/.test.ts"], environment: "jsdom"}

完整内容如下:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  // 单元测试配置
  test: {
    include: ["tests/**/*.test.ts"],
    environment: "jsdom"
  }
})

四、修改package.json配置文件,增加:

"scripts": {"test": "vitest", "coverage": "vitest run --coverage"}

完整内容如下:

{
  "name": "my-vue-app",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview",
    "test": "vitest",
    "coverage": "vitest run --coverage"
  },
  "dependencies": {
    "vue": "^3.2.45"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^4.0.0",
    "@vitest/coverage-c8": "^0.29.1",
    "@vue/test-utils": "^2.3.0",
    "jsdom": "^21.1.0",
    "vite": "^4.1.0",
    "vitest": "^0.29.1"
  }
}

五、在项目根目录下新建一个tests文件夹,然后在tests文件夹下新建一个单元测试文件demo.test.ts,完整内容如下:

import { describe, expect, it } from 'vitest'
import { mount } from '@vue/test-utils'
// 需要测试的组件页面
import Test from '@/pages/demo/test.vue'

const author1 = {
  name: 'pany',
  email: '939630029@qq.com',
  url: 'https://github.com/pany-ang',
}

const author2 = {
  name: 'pany',
  email: '939630029@qq.com',
  url: 'https://github.com/pany-ang',
}

describe('Test', () => {
  it('测试基础数据类型', () => {
    expect(1 + 1).toBe(2)
  })
  it('测试引用类型', () => {
    expect(author1).toEqual(author2)
  })
  it('组件正常渲染', () => {
    const wrapper: any = mount(Test)
    expect(wrapper.contains('div')).toBe(true)
  })
})

参考资料:

  1. vue官网
  2. vite中文网
  3. vitest中文网
  4. Vue Test Utils
  5. 年轻人的第一款单元测试框架
上一篇 下一篇

猜你喜欢

热点阅读