解决Vue单元测试的问题

  介绍

这篇文章主要讲解了解决Vue单元测试的问题,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。


这篇文章的代码使用业力,摩卡,柴,sinon-chai配合Vue的实例属性进行单元测试


由于我的g-icon是全局注册的,所以使用g-input组件时的时候g-icon是直接用的,所以测试时有关图标的代码永远是错的。

把g-icon局部注册的组件


模拟我在应用。vue里使用g-input组件

& lt; g-input v模型=癿essage"祝辞& lt;/g-input>

使用新的事件和调度模拟事件在组件上触发,虽然这个事件和我们实际的事件不一样,但名字一样就够了,测试回调函数自带的参数

它(“支持事件“,()=比;{   (“change",“input",“focus",“blur"]。forEach (eventName=比;{   vm=new构造函数({})。美元山();   const调=sinon.fake ();   vm。美元(eventName,回调);   让事件=new事件(eventName);   Object.defineProperty(事件,“target", {   价值:{值:“hi"},   可列举的:真   });   让inputElement=vm。美元el.querySelector (“input");   inputElement.dispatchEvent(事件);   期望(回调).to.have.been.calledWith (“hi");   });   });

测试这个组件事件触发时,回调的参数,由于自定义事件没有目标,我们需要自己写上去

值:{值:“hi"}第一个价值是defineProperty的


坑来自于下面一段代码

它(“接受gutter",函数(){   Vue.component (“g-row"、行);   Vue.component (“g-col"坳);   const div=document.createElement (“div");   document.body.appendChild (div);   div.innerHTML='   & lt; g-row地沟=?0“比;   & lt; g-col> & lt;/g-col>   & lt; g-col> & lt;/g-col>   & lt;/g-row>;   const vm=new Vue ({   艾尔:div   });   setTimeout(()=比;{   const行=vm。美元el.querySelector (“.row");   期望(getComputedStyle(行).marginRight) .to.eq (“-10 px");   期望(getComputedStyle(行).marginLeft) .to.eq (“-10 px");   const关口=vm。美元el.querySelectorAll (“.col");   期望(getComputedStyle(关口[0]).paddingRight) .to.eq (“10 px");   期望(getComputedStyle(关口[1]).paddingLeft) .to.eq (“10 px");   (完成);   vm。美元el.remove ();   vm。摧毁美元();   },0);   });

我使用直接在el上写入模板代码,所以我默认的从“进口Vue vue" (runtimeonly版本)无法编译这个代码,从“进口Vue . ./node_modules Vue/dist/vue.esm.js"使用上面引入即可

在没有模板选项是,el不替换


还是这个代码,先看以下测试两个组件关系

它(“接受gutter",函数(){   Vue.component (“g-row"、行);   Vue.component (“g-col"坳);   const div=document.createElement (“div");   document.body.appendChild (div);   div.innerHTML='   & lt; g-row地沟=?0“比;   & lt; g-col> & lt;/g-col>   & lt; g-col> & lt;/g-col>   & lt;/g-row>;   const vm=new Vue ({   艾尔:div   });   setTimeout(()=比;{   const行=vm。美元el.querySelector (“.row");   期望(getComputedStyle(行).marginRight) .to.eq (“-10 px");   期望(getComputedStyle(行).marginLeft) .to.eq (“-10 px");   const关口=vm。美元el.querySelectorAll (“.col");   期望(getComputedStyle(关口[0]).paddingRight) .to.eq (“10 px");   期望(getComputedStyle(关口[1]).paddingLeft) .to.eq (“10 px");   (完成);   vm。美元el.remove ();   vm。摧毁美元();   },0);   });

<强>先说为什么需要seTimeout

从创建和安装钩子说起,createElement和列表末尾在js代码是同步的,两个钩子分别在这两段代码后执行,钩子异步执行的。

由于我们在g-row组件中有安装钩子,所以我们必须得进行异步检测,否则我们在新的Vue之后立马进行测试,钩子还没执行完。

<强>摩卡异步测试

摩卡默认不执行异步,加入做参数,调用完成()就可以


每一个测试完成之后,都要写下面两条代码

vm。美元el.remove ();   vm。摧毁美元();

有两个作用:

    <李>销毁在页面中的数据李 <李>销毁在内存的数据

虽然js是单线程,但是还有一个dom线程

 var div=文档。getElementById (& # 39; xxx # 39;)
  div.onclick=function () {///代码
  }
  setTimeout(函数(){
  div. remove ()
  },3000)

解决Vue单元测试的问题