一、写在前面
这篇文章的代码使用karma,mocha,chai,sinon-chai配合Vue的实例属性进行单元测试
二、全局的组件的坑
由于我的g-icon是全局注册的,所以使用g-input组件时的时候g-icon是直接用的,所以测试时有关icon的代码永远是错的。
把g-icon局部注册的组件
三、在测试中触发点击事件
模拟我在app.vue里使用g-input组件
<g-input v-model="message"></g-input>使用new event 和 dispatch 模拟事件在组件上触发,虽然这个事件和我们实际的事件不一样,但名字一样就够了,测试回调函数自带的参数
it("支持事件", () => {
["change", "input", "focus", "blur"].forEach(eventName => {
vm = new Constructor({}).$mount();
const callback = sinon.fake();
vm.$on(eventName, callback);
let event = new Event(eventName);
Object.defineProperty(event, "target", {
value: { value: "hi" },
enumerable: true
});
let inputElement = vm.$el.querySelector("input");
inputElement.dispatchEvent(event);
expect(callback).to.have.been.calledWith("hi");
});
});测试这个组件事件触发时,回调的参数,由于自定义事件没有target,我们需要自己写上去
value: { value: “hi” }第一个value是defineProperty的
四、Vue的版本
坑来自于下面一段代码
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);
});我使用直接在el上写入template代码,所以我默认的import Vue from “vue”(runtimeonly版本)无法编译这个代码,import Vue from “../node_modules/vue/dist/vue.esm.js”使用上面引入即可
在没有template选项是,el不替换
五、异步测试
还是这个代码,先看以下测试两个组件关系










