让我们假设一个基本的 Bootstrap作为自定义 Vue 组件一部分的驱动 HTML 表单 MyForm.vue
<template>
<form>
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</template>
用于测试模板是否成功渲染的单元测试非常简单
describe('MyForm', () => {
let wrapper;
beforeEach(...);
it('Should be rendered', () => {
let field = wrapper.find('#email');
expect(field.element.value).toEqual('');
});
});
此行有效 field.element.value
有效,因为 field.element
是具有 value
的 native 类型 HtmlInputElement
> 属性。
如果我想访问复杂组件的属性(比如说 b-form-input)怎么办? ,Bootstrap-Vue 的默认输入元素? b-form-input
是 BFormInput
类型如何处理?只需将 HtmlElement
转换为 BFormInput
即可?
<template>
<b-form>
<b-form-group label="Email">
<b-form-input type="email" id="email"></b-form-input>
</b-form-group>
<b-button type="submit" variant="primary">Submit</button>
</b-form>
</template>
如何测试非原生组件?特别是类型安全意味着 TypeScript。有什么想法吗?
编辑 03/01/2020
关注muka.gergely我找到的答案this文章。 shallowMount
默认情况下会 stub 所有子组件,这也会阻止事件处理。此外,shallowMount 允许手动取消 stub 组件,在我的例子中,取消 stub b-form 和 b-button 进行提交事件测试。
const stubs = { // Originally intended to provide custom stubs, here used to unstub components
BButton,
BForm,
};
wrapper = shallowMount<MyComponent>(MyComponent, {stubs});
这会影响这些组件的渲染而不是 stub 。所有剩余组件(例如 b-form-input
)仍会自动 stub 。
最佳答案
在测试元素之前,您必须安装
元素。您不测试您编写的 Vue 组件,而是测试渲染的输出。
您应该添加 vue-test-utils 然后是您的单元测试库(很好支持 Jest 和 Mocha)。
- 您可以在这里找到vue-test-utils:https://www.npmjs.com/package/@vue/test-utils
- 有关 Vue 单元测试的更多信息:https://v2.vuejs.org/v2/guide/unit-testing.html
- 有关vue-test-utils的更多信息:https://vue-test-utils.vuejs.org/guides/#getting-started
这是 App.vue 的基本单元测试(使用 Vuetify 和 vue-router):
import Vue from 'vue'
import { shallowMount, createLocalVue } from '@vue/test-utils'
import Vuetify from 'vuetify'
import VueRouter from 'vue-router'
import App from '@/App';
Vue.use(Vuetify)
const localVue = createLocalVue()
localVue.use(VueRouter)
const router = new VueRouter()
describe('App.vue', () => {
let vuetify
beforeEach(() => {
vuetify = new Vuetify()
})
it('mounts and renders', () => {
const wrapper = shallowMount(App, { localVue, vuetify, router });
expect(wrapper.html()).toBeTruthy();
});
});
您可以看到我使用了 shallowMount()
,因为我对测试 App.vue 的子级不感兴趣(它们都有单独的单元测试)。如果是的话,那么我应该使用 mount()
来代替。
关于javascript - Vue.js - 具有复杂子项的单元测试组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60401840/