Vue.js-具有复杂子级的单元测试组件



让我们假设一个基本的Bootstrap驱动的HTML表单是自定义Vue组件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属性的本机类型HtmlInputElement

如果我想访问一个复杂组件的属性,比如Bootstrap Vue的默认输入元素b-form-input,该怎么办?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

根据穆卡的回答,我找到了这篇文章。默认情况下,shallowMount会清除所有子组件,这也会阻止事件处理。此外,shallowMount允许手动卸载组件,在我的情况下,卸载b-formb-button以提交事件测试。

const stubs = { // Originally intended to provide custom stubs, here used to unstub components
BButton,
BForm,
};
wrapper = shallowMount<MyComponent>(MyComponent, {stubs});

这会导致这些组件被渲染,而不是被存根化。所有剩余的组件,如b-form-input,仍然会自动存根。

在测试元素之前,必须先mount元素。您不测试您编写的Vue组件,而是测试渲染的输出。

您应该添加vue-test-utils,然后您的单元测试库(JestMocha都得到了很好的支持(。

  • 您可以在此处找到vue测试实用程序:https://www.npmjs.com/package/@vue/test实用程序
  • 有关Vue单元测试的更多信息:https://v2.vuejs.org/v2/guide/unit-testing.html
  • 有关vue测试实用程序的更多信息:https://vue-test-utils.vuejs.org/guides/#getting-已启动

以下是App.vue的基本单元测试(使用Vuetifyvue路由器(:

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()

最新更新