Vue Test Utils的简单使用

1,707 阅读1分钟

这是我参与2022首次更文挑战的第20天,活动详情查看:2022首次更文挑战

Vue Test til U 是一种实用功能,提供了一些 Vue 组件的方法测试。

这里写一些基本的使用方法

Vue测试工具的地址:test-utils.vuejs.org/guide/ 这是针对vue3的

安装

npm install --save-dev @vue/test-utils@next

一般我们都是通过Vue cli创建的工程,,可以使用如下命令:

vue add @vue/unit-jest

在package.json中查看我们的测试命令

image.png

查看测试文件夹 test/unit

image.png

能看到文件夹下存在example文件,文件内容如上

常用api

describe

创建一个将多个相关测试分组在一起的块 有两个参数,nameh和fn,通常的使用如下

describe('HelloWorld.vue', () => {
  ....
})

test

在测试文件中需要全部运行test的方法。该api有三个参数,分别是测试名称、测试函数、测试时间(一般情况下为0)

例如:

test('ceshimingcheng', () => {
    ...
})

// 简写
it('ceshimingcheng', () => {
    ...
})

mount

首先我们要显式引用mount,并挂在组件

例如

在里边我们可以执行我们的测试内容

import { mount } from '@vue/test-utils'

const wrapper = mount(Counter)

这样我们就得到了一个包裹器,通过包裹器我们可以访问vue的实例 创建一个包含被挂载和渲染的 Vue 组件的 Wrapper

shallowMount

和 mount 一样,创建一个包含被挂载和渲染的 Vue 组件的 Wrapper,不同的是被存根的子组件。

mount是完整的渲染,直接连子组件一同渲染了,shallowMount需要我们再单独处理这个一层。 如下

describe('HelloWorld.vue', () => {
  it('renders props.msg when passed', () => {
    const msg = 'new message'
    const wrapper1 = mount(HelloWorld, {
      props: { msg }
    })
    const wrapper2 = shallowMount(HelloWorld, {
      props: { msg }
    })
    console.log(wrapper1.html())
    console.log(wrapper2.html())
    // expect(wrapper.text()).toMatch(msg)
  })
})

image.png 未完待续.....