我有一个Vue.js组件,该组件显示BootstrapVue标语以响应提交错误。手动测试期间一切正常,但是相应的单元测试失败。
以下错误。
[vue-test-utils]: find did not return #submit-failure-banner, cannot call isVisible() on empty Wrapper
36 |
37 | const errorBanner = wrapper.find("#submit-failure-banner")
> 38 | expect(errorBanner.isVisible()).toBeTruthy()
| ^
39 | })
40 | })
41 |
it("shows an error message on post failure", async () => {
const wrapper = mount(NewSite, {
localVue,
provide: {
sites: new Sites(internalServerErrorRequestHandler)
}
});
const siteOwnerInput = wrapper.find('#new-site-owner-input');
siteOwnerInput.setValue(owner);
const saveButton = wrapper.find('#new-site-save');
saveButton.trigger('click');
await wrapper.vm.$nextTick();
const errorBanner = wrapper.find("#submit-failure-banner")
expect(errorBanner.isVisible()).toBeTruthy()
})
NewSite
组件的相关部分如下,从模板中的banner元素开始。
<b-alert id="submit-failure-banner" variant="danger" v-model="banners.submitFailure" dismissible>
{{ $t('$MESSAGE_SITE_SAVE_FAILED') }}
</b-alert>
export default class NewSite extends Vue {
@Inject('sites') private sites!: Sites
form = {
owner: ''
}
banners = {
submitFailure: false,
...
}
async postForm() {
return await this.sites.create({
owner: this.form.owner,
state: SiteStatus.NEW
}).save()
}
...
async onSave() {
if (!this.checkForm()) {
return;
}
try {
await this.postForm();
await this.$router.push({name: 'dashboard'})
} catch (_) {
this.banners.submitFailure = true;
}
}
Sites
类的相关部分仅使用请求处理程序执行POST请求。在生产环境中为axios
,在测试过程中为模拟请求处理程序。 internalServerErrorRequestHandler
的定义如下。
const internalServerErrorRequestHandler = {
post(url: string, data: any): Promise<Response> {
return Promise.reject()
}
}
我通过console.log
语句验证了html没有显示横幅。
我通过对BAlert
组件进行打桩,从而删除了transition
元素,从而解决了问题。我使用的存根如下:
<template>
<div :v-show="value" :id="id">
<slot/>
</div>
</template>
<script lang="ts">
import {Vue, Component, Prop} from "vue-property-decorator";
@Component
export default class BAlertStub extends Vue {
@Prop() value = false
@Prop() id = ""
}
</script>