vue2.x学习笔记(二十七)

接着前面的内容:https://www.cnblogs.com/yanggb/p/12682364.html

单元测试

vue cli拥有开箱即用的通过jest或mocha进行单元测试的内置选项。官方的vue test utils还提供了更多详细的指引和自定义设置。

简单的断言

你不必为了可测性在组件中做任何特殊的操作,导出原始设置就可以了:

<template>
  <span>{{ message }}</span>
</template>

<script>
  export default {
    data () {
      return {
        message: 'hello!'
      }
    },
    created () {
      this.message = 'bye!'
    }
  }
</script>

然后随着vue test utils导入组件,你就可以使用许多常见的断言(这里我们用的是jest风格的expect断言作为示例):

// 导入Vue Test Utils内的shallowMount和待测试的组件
import { shallowMount } from '@vue/test-utils'
import MyComponent from './MyComponent.vue'

// 挂载这个组件
const wrapper = shallowMount(MyComponent)

// 这里是一些Jest的测试,你也可以使用你喜欢的任何断言库或测试
describe('MyComponent', () => {
  // 检查原始组件选项
  it('has a created hook', () => {
    expect(typeof MyComponent.created).toBe('function')
  })

  // 评估原始组件选项中的函数的结果
  it('sets the correct default data', () => {
    expect(typeof MyComponent.data).toBe('function')
    const defaultData = MyComponent.data()
    expect(defaultData.message).toBe('hello!')
  })

  // 检查 mount 中的组件实例
  it('correctly sets the message when created', () => {
    expect(wrapper.vm.$data.message).toBe('bye!')
  })

  // 创建一个实例并检查渲染输出
  it('renders the correct message', () => {
    expect(wrapper.text()).toBe('bye!')
  })
})

编写可被测试的组件

很多组件的渲染输出由它的props决定。实际上,如果一个组件的渲染输出完全取决于它的props,那么它会让测试变得简单,就好像断言不同参数的纯函数的返回值。看下面的这个例子:

import { shallowMount } from '@vue/test-utils'
import MyComponent from './MyComponent.vue'

// 挂载元素并返回已渲染的组件的工具函数
function getMountedComponent(Component, propsData) {
  return shallowMount(Component, {
    propsData
  })
}

describe('MyComponent', () => {
  it('renders correctly with different props', () => {
    expect(
      getMountedComponent(MyComponent, {
        msg: 'Hello'
      }).text()
    ).toBe('Hello')

    expect(
      getMountedComponent(MyComponent, {
        msg: 'Bye'
      }).text()
    ).toBe('Bye')
  })
})

断言异步更新

出于vue是异步进行更新dom操作的情况,一些依赖dom更新结果的断言必须在【vm.$nextTick()】resolve之后进行:

// 在状态更新后检查生成的HTML
it('updates the rendered message when wrapper.message updates', async () => {
  const wrapper = shallowMount(MyComponent)
  wrapper.setData({ message: 'foo' })

  // 在状态改变后和断言 DOM 更新前等待一刻
  await wrapper.vm.$nextTick()
  expect(wrapper.text()).toBe('foo')
})

关于更深入vue单元测试的内容可以到vue test utils的官方文档查看。

"我还是很喜欢你,像细雨洒落八千里,淅淅沥沥。"

猜你喜欢

转载自www.cnblogs.com/yanggb/p/12682573.html