本文以Jest测试框架为例,介绍常用的接口和用法。第一次安装:创建项目时勾选UnitTesting,然后选择Jest。第二种:在项目根目录下执行vueadd@vue/cli-plugin-unit-Jest常用apidescribe:创建测试组test(别名:it):创建测试用例expect:提供各种判断测试结果是否满足的方法预期匹配函数toBe:判断是否相等的值类型toEqual:判断是否相等的引用类型toBeNulltoBeUndefinedtoBedefinedtoBeNaNtoBeTruthytoBeFalsytoContain:数组是否包含toHaveLenth:数组长度toThrow:异常匹配生命周期beforeAll:在所有测试用例执行之前触发(只触发一次)beforeEach:每个测试用例执行前触发afterAll:所有测试用例执行完后触发(只触发一次)afterEach:每个测试用例触发组件mount执行后:挂载组件,包括子组件shallowMount:只挂载当前组件,不包括子组件Wrapper:返回vnode挂载vm后测试相关方法:返回vue实例类s:返回相关类名的dom或者集合find:返回满足一个条件的domfindAll:返回满足所有条件的domhtml:返回html字符串text:返回内容字符串setData:设置组件datasetProps:设置组件propstrigger:触发事件使用//utils.jsexport函数add(a,b){returna+b}exportclassCount{constructor(){this.number=1}increase(){this.number++}decreate(){this.number--}}exportfunctiontimeout(fn){setTimeout(function(){fn()},2000)}exportfunctionpromise(){返回新Promise((resolve,reject)=>{setTimeout(()=>{resolve(2)},2000)})}常规测试const{add}=require('./utils')test('add1+2等于3',()=>{expect(add(1,2)).toBe(3)})grouptestconst{Count}=require('./utils')describe('grouptest',()=>{letobj=nullbeforeAll(()=>{console.log('在所有测试执行之前触发')})beforeEach(()=>{//利用生命周期避免类对象状态相互影响console.log('每次测试执行前触发')obj=newCount()})afterAll(()=>{console.log('所有测试执行后触发')})afterEach(()=>{console.log('每次测试执行后触发')})test('测试增加',()=>{expect(obj.increase()).toBe(2)})test('测试减少',()=>{expect(obj.decrease()).toBe(0)})})异步代码测试调用donefunctionconst{timeout}=require('./utils')test('异步代码测试',done=>{timeout(()=>{expect(2+2).toBe(4)done()})})跳过等待时间const{超时}=require('./utils')test('异步代码测试',done=>{jest.useFakeTimers()constfn=jest.fn()timeout(fn)jest.advanceTimersByTime(2000)expect(fn).toHaveBeenCalledTimes(1)})promise函数处理方法一const{promise}=require('./utils')test('promise',()=>{returnpromise().then(res=>{expect(res).toBe(2)})})方法二const{promise}=require('./utils')test('promise',()=>{returnexpect(promise()).resolves.toBe(2)})组件测试//@/components/Modal.vue
