VueJs2.0 专题
您的位置:JS框架 > VueJs2.0专题 > Vue.js 2.0 单元测试
Vue.js 2.0 单元测试
作者:--    发布时间:2019-11-20

配置和工具

任何兼容基于模块的构建系统都可以正常使用,但如果你需要一个具体的建议,可以使用 karma 进行自动化测试。它有很多社区版的插件,包括对 webpack 和 browserify 的支持。更多详细的安装步骤,请参考各项目的安装文档,通过这些 karma 配置的例子可以快速帮助你上手(webpack 配置,browserify 配置)。

简单的断言

在测试的代码结构方面,你不必为了可测试在你的组件中做任何特殊的操作。只要导出原始设置就可以了:

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

当测试的组件时,所要做的就是导入对象和 vue 然后使用许多常见的断言:

// 导入 vue.js 和组件,进行测试
import vue from 'vue'
import mycomponent from 'path/to/mycomponent.vue'
// 这里是一些 jasmine 2.0 的测试,你也可以使用你喜欢的任何断言库或测试工具。
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', () => {
    const vm = new vue(mycomponent).$mount()
    expect(vm.message).tobe('bye!')
  })
  // 创建一个实例并检查渲染输出
  it('renders the correct message', () => {
    const ctor = vue.extend(mycomponent)
    const vm = new ctor().$mount()
    expect(vm.$el.textcontent).tobe('bye!')
  })
})

编写可被测试的组件

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

<template>
  <p>{{ msg }}</p>
</template>
<script>
  export default {
    props: ['msg']
  }
</script>

你可以在不同的 props 中,通过 propsdata 选项断言它的渲染输出:

import vue from 'vue'
import mycomponent from './mycomponent.vue'
// 挂载元素并返回已渲染的文本的工具函数 
function getrenderedtext (component, propsdata) {
  const ctor = vue.extend(component)
  const vm = new ctor({ propsdata }).$mount()
  return vm.$el.textcontent
}
describe('mycomponent', () => {
  it('render correctly with different props', () => {
    expect(getrenderedtext(mycomponent, {
      msg: 'hello'
    })).tobe('hello')
    expect(getrenderedtext(mycomponent, {
      msg: 'bye'
    })).tobe('bye')
  })
})

断言异步更新

由于 vue 进行异步更新dom的情况,一些依赖dom更新结果的断言必须在 vue.nexttick回调中进行:

// 在状态更新后检查生成的 html
it('updates the rendered message when vm.message updates', done => {
  const vm = new vue(mycomponent).$mount()
  vm.message = 'foo'
  // 在状态改变后和断言 dom 更新前等待一刻
  vue.nexttick(() => {
    expect(vm.$el.textcontent).tobe('foo')
    done()
  })
})

我们计划做一个通用的测试工具集,让不同策略的渲染输出(例如忽略子组件的基本渲染)和断言变得更简单。

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册