我已经在Vue.js中为我的项目构建了一个简单的ErrorBoundary组件,并且正在努力为其编写单元测试。组件的代码如下:
<template>
<div class="overvue-error-boundary">
<slot v-if="!error" />
<div class="error-message" v-else>Something went horribly wrong here.</div>
</div>
</template>
<script>
export default {
data () {
return {
error: false
}
},
errorCaptured (error, vm, info) {
this.error = true;
}
}
</script>
我创建了一个ErrorThrowingComponent,它在 created()生命周期挂钩上引发了错误,因此我可以测试ErrorBoundary:
const ErrorThrowingComponent = Vue.component('error-throwing-component', {
created() {
throw new Error(`Generic error`);
},
render (h) {
return h('div', 'lorem ipsum')
}
});
describe('when component in slot throws an error', () => {
it('renders div.error-message', () => {
// this is when error is when 'Generic error' is thrown by ErrorThrowingComponent
const wrapper = shallowMount(OvervueErrorBoundary, {
slots: {
default: ErrorThrowingComponent
}});
// below code is not executed
expect(wrapper.contains(ErrorThrowingComponent)).to.be.false;
expect(wrapper.contains('div.error-message')).to.be.true;
});
});
问题是当我尝试实际安装它时,ErrorThrowingComponent会引发错误(从而使整个测试失败)。有什么办法可以防止这种情况发生?
编辑:我要实现的目的是在 ErrorBoundary 组件的默认插槽中实际 mount 组件,以断言 ErrorBoundary >将显示错误消息,而不是插槽。这是我首先创建ErrorThrowingComponent的方式。但是我无法断言ErrorBoundary的行为,因为尝试创建包装器时出现错误。
答案 0 :(得分:2)
对于在这里遇到类似问题的任何人:我已经在Discord的Vue Land的#vue-testing频道上提出了这个问题,他们建议将整个错误处理逻辑移至一个函数,该函数将从errorCaptured()调用钩,然后只需测试此功能。这种方法对我来说似乎是明智的,所以我决定将其发布在这里。
重构的 ErrorBoundary 组件:
<template>
<div class="error-boundary">
<slot v-if="!error" />
<div class="error-message" v-else>Something went horribly wrong here. Error: {{ error.message }}</div>
</div>
</template>
<script>
export default {
data () {
return {
error: null
}
},
methods: {
interceptError(error) {
this.error = error;
}
},
errorCaptured (error, vm, info) {
this.interceptError(error);
}
}
</script>
使用vue-test-utils进行单元测试:
describe('when interceptError method is called', () => {
it('renders div.error-message', () => {
const wrapper = shallowMount(OvervueErrorBoundary);
wrapper.vm.interceptError(new Error('Generic error'));
expect(wrapper.contains('div.error-message')).to.be.true;
});
});