
在目前我的所有代码中,只有在toast.vue
里写了style
:
setLineHeight() {
this.$nextTick(() => {
this.$refs.line.style.height = `${
this.$refs.toast.getBoundingClientRect().height
}px`;
});
}
而且这个函数只在mounted
中执行了一次:
mounted() {
this.setLineHeight();
this.execAutoClose();
}
于是我在mounted
、和setLineHeight
中都log
了这个style
mounted() {
console.log(this.$el.outerHTML)
this.setLineHeight();
this.execAutoClose();
}
setLineHeight() {
this.$nextTick(() => {
console.log(this.$refs)
console.log(this.$refs.line)
this.$refs.line.style.height = `${
this.$refs.toast.getBoundingClientRect().height
}px`;
});
}
发现了this.$refs.line
是undefined
因为后两个log
是在nextTick
中执行的,和第一个log
存在一点点的时间间隙
再看我的测试代码
it('接受 closeButton',() => {
const callback = sinon.fake();
const Constructor = Vue.extend(Toast)
const vm = new Constructor({
propsData: {
closeButton: {
text: '关闭他',
callback,
}
}
}).$mount()
let closeButton = vm.$el.querySelector('.close')
expect(closeButton.textContent.trim()).to.eq('关闭他')
closeButton.click()
expect(callback).to.have.been.called
})
发现了在mounted
后立马接了一个closeButton.click()
,触发了我写的关闭函数,把标签都摧毁了
close() {
this.$el.remove();
this.$emit("close");
this.$destroy();
}
所以经过分析,是click
触发关闭函数太快了,所以this.$refs.line
的结果是undefined
因此解决方法就是把click
放在一个setTimeout
函数里
setTimeout(() => {
closeButton.click()
expect(callback).to.have.been.called
done() //测试用例异步需要执行一个done
},200)
这样就通过了测试用例,而且还没有讨厌的报错,强迫症患者舒服了。
网友评论