一常挚、Mocha簡介
Vue CLI 擁有開箱即用的通過 Jest 或 Mocha 進行單元測試的內(nèi)置選項为障。
Mocha--github
https://mochajs.org/
測試示例
https://vue-test-utils.vuejs.org/zh-cn/
二虑润、安裝組件
npm install --save-dev vue-test-utils
二弥喉、創(chuàng)建測試
- 創(chuàng)建測試組件
Test.vue
<template>
<span>{{ message }}</span>
</template>
<script>
export default {
data () {
return {
message: 'hello!'
}
},
created () {
this.message = 'bye!'
}
}
</script>
- 創(chuàng)建測試腳本
Test.spec.js
// 引入測試組件
import { expect } from 'chai';
import { shallowMount } from '@vue/test-utils';
// 測試組件
import Test from '@/components/Test.vue';
// 創(chuàng)建測試套件馒疹,一個測試組件寫一個測試套件
describe('Test.vue', () => {
// 測試用例污尉,用來測試不同的方法或者顯示的內(nèi)容
it('測試通過', () => {
// 定義數(shù)據(jù)
const message = 'bye!';
// shallowMount 掛載數(shù)據(jù)
const wrapper = shallowMount(Test, {
propsData: { message },
});
// 斷言:頁面中是否有message所渲染出來的內(nèi)容
expect(wrapper.text()).to.include(message);
});
});
測試腳本應(yīng)該包含一個或多個describe, 每個describe塊應(yīng)該包括一個或多個it塊describe塊稱為"測試套件"(test suite), 表示一組相關(guān)的測試。它是一個函數(shù), 第一個參數(shù)是測試套件的名稱(通常寫測試組件的名稱, 這里即為Test.vue), 第二個參數(shù)是一個實際執(zhí)行的函數(shù)损拢。
it塊稱為"測試用例"(test case), 表示一個單獨的測試, 是測試的最小單位. 它也是一個函數(shù), 第一個參數(shù)是測試用例的名稱(通常描述你的斷言結(jié)果), 第二個參數(shù)是一個實際執(zhí)行的函數(shù).
三、運行測試
npm run test:unit
測試結(jié)果:
測試結(jié)果
四撒犀、Chai斷言庫
所謂斷言, 就是判斷源碼的實際執(zhí)行結(jié)果與預(yù)期結(jié)果是否一致, 如果不一致, 就會拋出錯誤福压。
// 相等或不相等
expect(1 + 1).to.be.equal(2);
expect(1 + 1).to.be.not.equal(3);
// 布爾值為true
expect('hello').to.be.ok;
expect(false).to.not.be.ok;
// typeof
expect('test').to.be.a('string');
expect({ foo: 'bar' }).to.be.an('object');
expect(foo).to.be.an.instanceof(Foo);
// include
expect([1,2,3]).to.include(2);
expect('foobar').to.contain('foo');
expect({ foo: 'bar', hello: 'universe' }).to.include.keys('foo');
// empty
expect([]).to.be.empty;
expect('').to.be.empty;
expect({}).to.be.empty;
// match
expect('foobar').to.match(/^foo/);
五、Chai斷言庫vue-test-utils的常用API
find(): 返回匹配選擇器的第一個DOM節(jié)點或Vue組件的wrapper, 可以使用任何有效的選擇器
text(): 返回wrapper的文本內(nèi)容
html(): 返回wrapper DOM的HTML字符串
it('find()/text()/html()方法', () => {
const wrapper = mount(Counter);
const h3 = wrapper.find('h3');
expect(h3.text()).to.equal('Counter.vue');
expect(h3.html()).to.equal('<h3>Counter.vue</h3>');
})
trigger(): 在該 wrapper DOM 節(jié)點上觸發(fā)一個事件或舞。
it('trigger()方法', () => {
const wrapper = mount(Counter);
const buttonOfSync = wrapper.find('.sync-button');
buttonOfSync.trigger('click');
buttonOfSync.trigger('click');
const count = Number(wrapper.find('.num').text());
expect(count).to.equal(2);
})
setData(): 設(shè)置data的屬性并強制更新
it('setData()方法',() => {
const wrapper = mount(Counter);
wrapper.setData({foo: 'bar'});
expect(wrapper.vm.foo).to.equal('bar');
})