概念
- Karma: google的一套前端测试运行框架.主要工作
- Karma启动一个web服务,生成包含js源代码和测试脚本的页面.
- 运行浏览器加载页面,并显示测试结果.
- 如果开启测试,当文件有修改时,继续执行以上过程.
mocha js测试框架. 测试代码的语法就是这个. 别的还有Jasmine,Tape,总之好多都不认识..😂
PlantomJs 基于WebKit的服务器端JavaScript API。它全面支持web而不需浏览器支持,其快速,原生支持各种Web标准:DOM处理,CSS选择器,JSON,Canvas,可以用于
页面自动化
,网络监测
,网页截屏
,以及无界面测试
等。 抄的,那么简单讲,就是不用浏览器显示测试结果的服务端.Coverage 代码覆盖率,衡量测试脚本的质量
vue-cli 的测试就是单元测试,和计算单元测试的覆盖率
mocha 简单教程
- 大致的最简单写法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// 写引用
import Vue from 'vue'
import MyComponent from '~/hello/hello.vue'
// 写函数,官网上抄的
// helper function that mounts and returns the rendered text
// 挂载元素并返回已渲染的文本
function getRenderedText (Component, propsData) {
const Ctor = Vue.extend(Component)
const vm = new Ctor({ propsData: propsData }).$mount()
return vm.$el.textContent
}
// 写test suite, 就是这个describe
// 嵌套写test case, 就是it
// 嵌套里写断言 expect
// 大概意思就是,断言里的结果要和toBe里的一致才算测试通过.
describe('这里写一个说明', () => {
it('renders correctly with different props', () => {
expect(getRenderedText(MyComponent, {
msg: 'Hello'
})).toBe('Hello')
expect(getRenderedText(MyComponent, {
msg: 'Bye'
})).toBe('Bye')
})
})
describe('这里是另一个说明', () => {
// 检查原始组件选项
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!')
})
})
然而这是错的,也不知道是版本还是什么,toBe要写成to.equal,不是toBe,也不是to.be.equal,这样就通过了
覆盖率 Coverage,主要考虑四项,vue-cli里是全自动的,不用什么操作.
看不懂到底要说明啥
- Statements //声明
- Branches //分支
- Functions // 函数
- Lines //线
总结vue要测试的地方
- 检查是否函数
- 检查函数结果
- 检查组件实例
- 检查渲染输出
另外:$mount() 的功能,是手动挂载,就是当vue实例没有el属性时,该实例就没有挂载到dom中.大概也就在测试里用了.
假如需要延迟挂载,可以在之后手动调用vm.$mount()来挂载.例如1
2
3
4
5
6
7
8
9
10
11
12
13<div id="app">
{{a}}
</div>
<button onclick="test()">挂载</button>
<script>
var obj = {a: 1}
var vm = new Vue({
data: obj
})
function test() {
vm.$mount("#app");
}
</script>
输出html的报告 mochawesome