Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vue 单元测试 #27

Open
ChenJiaH opened this issue Aug 2, 2019 · 0 comments
Open

Vue 单元测试 #27

ChenJiaH opened this issue Aug 2, 2019 · 0 comments
Labels

Comments

@ChenJiaH
Copy link
Owner

ChenJiaH commented Aug 2, 2019

首发于微信公众号《前端成长记》,写于 2018.05.31

背景

没有测试用例的代码库都是不完整的,使用者也会诚惶诚恐。所以本文简单介绍一下如何对 Vue 文件进行单元测试。

测试步骤

  1. 通过 vue-cli 脚手架构架项目,选中 karma && Mocha 后会自动初始化一个 Helloworld.spec.js 的测试用例并安装对应所需依赖(这步也可以手动安装依赖)

  2. 修改 HelloWorld.vue 文件

<template>
  <div>
    <h3>Helloworld</h3>
    <p class="num">{{ num }}</p>
    <button @click="add">增加</button>
  </div>
</template>
<script>
  export default {
    data () {
      return {
        num : 0
      }
    },
 
    methods: {
      add() {
        this.num++
      }
    }
  }
</script>
  1. 修改 HelloWorld.spec.js
import Vue from 'vue'
import HelloWorld from '@/components/HelloWorld'
describe('HelloWorld.vue', () => {
  it('h3的初始值应为HelloWorld', () => {
    const Constructor = Vue.extend(HelloWorld)
    const vm = new Constructor().$mount()
    expect(vm.$el.querySelector('h3').textContent).to.equal('HelloWorld')
  })
  it('点击按钮后,num应为1', () => {
    const Constructor = Vue.extend(HelloWorld)
    const vm = new Constructor().$mount()
    const button = vm.$el.querySelector('button')
    const clickEvent = new window.Event('click')
    button.dispatchEvent(clickEvent)
    vm._watcher.run()
    expect(vm.$el.querySelector('.num').textContent).to.equal(1)
  })
})

当然,你也可以选择使用 vue-test-utils 来缩减代码量

npm install vue-test-utils --save-dev

然后上面的代码可以修改为

import { mount } from 'vue-test-utils'
import { expect } from 'chai'
import HelloWorld from '@/components/HelloWorld'
describe('HelloWorld.vue', () => {
  it('h3的初始值应为HelloWorld', () => {
    const wrapper = mount(HelloWorld)
    expect(wrapper.find('h3').text()).to.equal('HelloWorld')
  })
  it('点击按钮后,num应为1', () => {
    const wrapper = mount(HelloWorld)
    const button = wrapper.find('button')
    // 点击按钮修改
    button.trigger(click)
    // 或者直接修改数据
    // wrapper,setData({num: 1})
    expect(wrapper.find('.num').text()).to.equal(1)
  })
})
  1. 执行测试命令
npm run test

结尾

至此,一个简单的 Vue 组件单元测试就完成了。

代码库有较为完整的测试用例也会更加的可靠,你们觉得呢?

(完)


本文为原创文章,可能会更新知识点及修正错误,因此转载请保留原出处,方便溯源,避免陈旧错误知识的误导,同时有更好的阅读体验
如果能给您带去些许帮助,欢迎 ⭐️star 或 ✏️ fork
(转载请注明出处:https://chenjiahao.xyz)

@ChenJiaH ChenJiaH added the vue.js label Aug 2, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant