// 每个describe块应该包括一个或多个it块,称为测试用例(test case)
it('should render correct contents', () => {
const Constructor = Vue.extend(Hello) // 获得Hello组件实例
const vm = new Constructor().$mount() // 将组件挂在到DOM上
//断言:DOM中class为hello的元素中的h1元素的文本内容为Welcome to Your Vue.js App
expect(vm.$el.querySelector('.hello h1').textContent)
.to.equal('Welcome to Your Vue.js App')
})
})
需要知道的知识点:
测试脚本都要放在 test/unit/specs/ 目录下。
脚本命名方式为 [组件名].spec.js。
所谓断言,就是对组件做一些操作,并预言产生的结果。如果测试结果与断言相同则测试通过。
单元测试默认测试 src 目录下除了 main.js 之外的所有文件,可在 test/unit/index.js 文件中修改。
Chai断言库中,to be been is that which and has have with at of same 这些语言链是没有意义的,只是便于理解而已。
测试脚本由多个 descibe 组成,每个 describe 由多个 it 组成。
了解异步测试
it('异步请求应该返回一个对象', done => {
request
.get('https://api.github.com')
.end(function(err, res){
expect(res).to.be.an('object');
done();
});
});了解一下 describe 的钩子(生命周期)
describe('hooks', function() { before(function() {
// 在本区块的所有测试用例之前执行
});
after(function() {
// 在本区块的所有测试用例之后执行
});
beforeEach(function() {
// 在本区块的每个测试用例之前执行
});
afterEach(function() {
// 在本区块的每个测试用例之后执行
});
// test cases
});
实践
上面简单介绍了单元测试的用法,下面来动手在Vue中进行单元测试!
util.js
从Vue官方的demo可以看出,对于Vue的单元测试我们需要将组件实例化为一个Vue实例,有时还需要挂载到DOM上。
const Constructor = Vue.extend(Hello) // 获得Hello组件实例
const vm = new Constructor().$mount() // 将组件挂载到DOM上以上写法只是简单的获取组件,有时候我们需要传递props属性、自定义方法等,还有可能我们需要用到第三方UI框架。所以以上写法非常麻烦。
这里推荐Element的单元测试工具脚本Util.js,它封装了Vue单元测试中常用的方法。下面demo也是根据该 Util.js来写的。
这里简单注释了下各方法的用途。
/**
* 回收 vm,一般在每个测试脚本测试完成后执行回收vm。










