赞
踩
Vitest 旨在将自己定位为 Vite 项目的首选测试框架,即使对于不使用 Vite 的项目也是一个可靠的替代方案。它本身也兼容一些Jest的API用法。
- // npm
- npm install -D vitest
- // yarn
- yarn add -D vitest
- // pnpm
- pnpm add -D vitest
注意:vitest的版本应与你的项目依赖兼容,建议使用最新版本以获得最佳性能和功能。
Vitest的配置可以通过多种方式实现,包括在package.json中直接配置,或者创建一个专门的配置文件(如vitest.config.ts或vitest.config.js)。
在package.json的scripts部分添加一个测试脚本:
- "scripts":{
- "test":"vitest"
- }
这样就可以通过npm run test 或pnpm test来执行测试了
对于更复杂的配置,你可以创建一个vitest.config.ts或vitest.config.js文件。例如:
- /// <reference types="vitest">
- import { defineConfig } from "vite";
- import vue from "@vitejs/plugin-vue";
- import * as path from "path";
-
- // https://vitejs.dev/config/
- export default defineConfig({
- // 单元测试
- test: {
- globals: true, //全局注册
- environment: 'jsdom', // 模拟浏览器环境
- },
- resolve: {
- //设置别名
- alias: {
- "@": path.resolve(__dirname, "src"),
- },
- },
- plugins: [vue()],
- });
在你的Vue项目中,你可以为组件、函数、工具等编写测试。Vitest支持多种测试文件命名方式,但通常建议使用.test.ts或.spec.ts作为测试文件的扩展名。
例如,如果你有一个名为utils.js的文件,你可以创建一个utils.test.ts文件来编写它的测试。
- import { sum } from "../utils/index";
- describe('sum', () => {
- test('should return 0 when num is 0', () => {
- expect(sum(1, 1)).toEqual(2);
- });
-
- it('should return 1 when num is 1', () => {
- expect(sum(1, 4)).toEqual(5);
- });
-
- it('should return 1 when num is 2', () => {
- expect(sum(3, 3)).toBe(6);
- });
- });
最后,运行 npm run test、yarn test 或 pnpm test,具体取决于你的包管理器,Vitest 将打印此消息:
测试文件
- import { describe, it, expect } from 'vitest';
- import { mount } from '@vue/test-utils';
- import Button from './Button.vue';
-
- describe('Button.vue', () => {
- it('renders props.label when passed', () => {
- const wrapper = mount(Button, {
- props: {
- label: 'Click me',
- },
- });
- expect(wrapper.text()).toContain('Click me');
- });
-
- it('emits a click event when clicked', () => {
- const wrapper = mount(Button, {
- props: {
- label: '测试 Button',
- },
- attachToDocument: true,
- });
- wrapper.trigger('click');
- // 验证是否发射了 click 事件
- expect(wrapper.emitted().click).toBeTruthy();
- });
- });
最后,运行 npm run test、yarn test 或 pnpm test,具体取决于你的包管理器,Vitest 将打印此消息:
错误示例:
报错提醒!!!
原因:vitest是运行在Node.js环境的,没有document对象,因此需要借助jsdom来实现。
jsdom 是一个在 Node.js 环境中使用的纯 JavaScript 实现的 DOM(文档对象模型),它模拟了足够多的浏览器环境,使得你能够在服务器端(如 Node.js 应用程序)中运行那些原本只能在浏览器中运行的脚本。
- // npm
- npm install -D jsdom
- // yarn
- yarn add -D jsdom
- // pnpm
- pnpm add -D jsdom
Vitest还提供了许多其他配置选项,如支持TypeScript、模拟DOM环境、生成测试覆盖率报告等。你可以根据项目的具体需求来配置这些选项。
开发者
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。