详解关于Vue单元测试的几个坑

2020-06-16 06:42:08易采站长站整理

it("接受gutter", function(done) {
Vue.component("g-row", Row);
Vue.component("g-col", Col);
const div = document.createElement("div");
document.body.appendChild(div);
div.innerHTML = `
<g-row gutter="20">
<g-col></g-col>
<g-col></g-col>
</g-row>`;
const vm = new Vue({
el: div
});
setTimeout(() => {
const row = vm.$el.querySelector(".row");
expect(getComputedStyle(row).marginRight).to.eq("-10px");
expect(getComputedStyle(row).marginLeft).to.eq("-10px");
const cols = vm.$el.querySelectorAll(".col");
expect(getComputedStyle(cols[0]).paddingRight).to.eq("10px");
expect(getComputedStyle(cols[1]).paddingLeft).to.eq("10px");
done();
vm.$el.remove();
vm.$destroy();
}, 0);
});

先说为什么需要seTimeout

从created和mounted钩子说起,createElement和appendChild在js代码是同步的,两个钩子分别在这两段代码后执行,钩子异步执行的。

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

mocha异步测试

mocha默认不执行异步,加入done参数,调用done()就可以

六、垃圾回收

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


vm.$el.remove();
vm.$destroy();

有两个作用:

销毁在页面中的数据
销毁在内存的数据

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


var div = document. getElementById('xxx')
div.onclick = function() {
///code
}
setTimeout(function(){
div. remove()
}, 3000)

现在我们讨论,什么时候div上的函数被回收

函数被全局变量div上的onlick引用了

div.remove()只是在页面删掉了,没有被内存删掉


var div = document. getElementById('xxx')
div.onclick = function() {
///code
}
setTimeout(function(){
div = mull
}, 3000)

这个函数并没有被删除,函数是写在dom上的,div变量只是引用了dom对象


var div = document. getElementById('xxx')
div.onclick = function() {
///code
}
setTimeout(function(){
var div2 = document. getElementById('xxx')
}, 3000)

div= null和div.remove同时做就可以了,分别从内存和dom上删除了

ie有bug,即使这样都删不了,div.onlick = null 可以

到此这篇关于关于Vue单元测试的几个坑的文章就介绍到这了,更多相关 Vue单元测试 内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!