教你如何编写Vue.js的单元测试的方法

2020-06-16 06:11:26易采站长站整理


// find button
const button = ListComponent.$el.querySelector('button');

为了模拟一个点击,我们需要将按钮传递给一个新的事件对象。在测试环境中,List组件不会监听任何事件,因此我们需要手动运行监视器。


// simulate click event
const clickEvent = new window.Event('click');
button.dispatchEvent(clickEvent);
ListComponent._watcher.run();

最后,我们需要检查newItem是否显示,我们已经知道如何从第一个测试中完成!我们可能还想检查newItem是否存储在列表数组中。


//assert list contains new item
expect(ListComponent.$el.textContent).to.contain('brush my teeth');
expect(ListComponent.listItems).to.contain('brush my teeth');

以下是完整的测试文件:


import List from '@/components/List';
import Vue from 'vue';

describe('List.vue', () => {
it('displays items from the list', () => {
const Constructor = Vue.extend(List);
const ListComponent = new Constructor().$mount();
expect(ListComponent.$el.textContent).to.contain('play games');
})

it('adds a new item to list on click', () => {
// build component
const Constructor = Vue.extend(List);
const ListComponent = new Constructor().$mount();

// set input value
ListComponent.newItem = 'brush my teeth';

// simulate click event
const button = ListComponent.$el.querySelector('button');
const clickEvent = new window.Event('click');
button.dispatchEvent(clickEvent);
ListComponent._watcher.run();

// assert list contains new item
expect(ListComponent.$el.textContent).to.contain('brush my teeth');
expect(ListComponent.listItems).to.contain('brush my teeth');
})
})

现在我们可以再次运行我们的测试,应该会显示绿色!

希望这段代码对你来说能够很清楚,但是它不是特别容易理解,特别是对于第一次进行VueJS测试的人来说。有一个VueJS实用程序库,其中包含了一些更复杂的外观代码。要使用它,我们可以转到我们的项目根目录并运行以下命令:


npm install avoriaz

现在我们可以隐藏mount()之后的Vue组件的设置,并且为了单击按钮,我们需要的是两行代码:find()该按钮和dispatch() )点击事件。


import { mount } from 'avoriaz';
import List from '@/components/List';
import Vue from 'vue';

describe('List.vue', () => {
// previous tests ..

it('adds new item to list on click with avoriaz', () => {
// build component
const ListComponent = mount(List);