当我初次听到单元测试时,心里的第一感觉就两个字nb,然后就是疑惑,这是啥,干啥用,对代码又有什么帮助?接下来我会细细说一说我在学习以及应用单元测试的一些心得。(安装教程不再叙述,按照文档教程自行学习)
学习新知识,有中文文档当然是最好的啦!
Vue Test Utils
jest中文文档
import { shallowMount } from '@vue/test-utils'
import Foo from './Foo.vue'
describe('Foo', () => {
const wrapper = shallowMount(Foo)
})
{{name}}
{{name}}{{text}}
{{text}}
import { shallowMount } from '@vue/test-utils'
import Foo from './Foo.vue'
describe('Foo', () => {
const wrapper = shallowMount(Foo)
console.log(Wrapper.classes()) //['jest','name','test']
console.log(Wrapper.classes('jest')) //true
console.log(Wrapper.find('name').text()) //返回第一个class是name的dom的内容 王大大
console.log(Wrapper.findAll('name')) //返回dom数组
console.log(Wrapper.findAll('name').at(0)) //取dom数组中的第一个
Wrapper.setData({text : 1})
console.log(Wrapper.vm.text) //1
Wrapper.setProps({name : "李大大"})
console.log(Wrapper.vm.name) //李大大
Wrapper.find('text').trigger("click")
console.log(Wrapper.vm.text) // 2
})
import { shallowMount } from '@vue/test-utils'
import Foo from './Foo.vue'
const wrapper = shallowMount(Foo, {
data() {
return {
bar: 'my-override'
}
},
propsData: {
msg: 'aBC'
}
mocks: {
$route: {
query: {
aaa: '1',
}
},
$router: {
push: jest.fn(),
replace: jest.fn(),
}
}
})
describe('Foo', () => {
expect(2 + 2).toBe(4)
expect(null).toBeNull()
expect(undefined).toBeUndefined()
let a = 1;
expect(a).toBeDefined()
a = 'ada';
expect(a).toBeNaN()
a = true;
expect(a).toBeTruthy()
a = false;
expect(a).toBeFalsy()
a = [1,2,3];
expect(a).toContain(2)
expect(a).toHaveLength(3)
a = {a:1};
expect(a).toEqual({a:1})
})
import { shallowMount } from '@vue/test-utils'
import Foo from './Foo.vue'
const wrapper = shallowMount(Foo, {
mocks: {
$router: {
push: jest.fn(),
replace: jest.fn(),
}
}
})
wrapper.find(“jest").trigger("click");
expect(wrapper.vm.$router.push).toBeCalled();
wrapper.find(“jest").trigger("click");
expect(wrapper.vm.$router.push).toBeCalledTimes(2);
promise模拟
jest.mock('@root/api'); //模拟api请求函数
import {getList} from '@root/api';
const listJson = JSON.parse(require('fs').readFileSync('./mock/getList.json')); //引入mock好的json数据
getList.mockResolvedValue(Promise.resolve(listJson)); //模拟promise返回
getList().then(res => {
expect(res).toEqual(listJson);
})
说了这么多,那为什么要使用单测呢。在看完上面的描述我想大家也是一头郁闷,单测有用吗?答案当然是有。下面举个例子:
import { shallowMount } from '@vue/test-utils'
import Foo from './Foo.vue'
const wrapper = shallowMount(Foo)
这时候就会报错data.name,因为data不一定有值。正确案例如下
说白了就是让你的代码逻辑更符合预期结果。
目前在vue中用到的一些基本知识都已经总结完了,如果以后在工作中使用了新的api,时间充裕的情况下我会持续更新哦~
一起加油吧少年,对了,最后说一句和文章无关的话–“娶妻娶贤,纳妾纳色”
别多想,就是最近听到比较记忆犹新的一句。