【发布时间】:2018-11-05 06:07:44
【问题描述】:
我一直坚持为 Vue.js 组件编写单元测试,断言将特定 CSS 类添加到模板中。
这是我的模板:
<template>
<div id="item-list" class="item-list">
<table id="item-list-lg" class="table table-hover nomargin hidden-xs hidden-sm hidden-md">
<thead>
<tr>
<th>Name</th>
<th>Included modules</th>
</tr>
</thead>
<tbody>
<tr v-bind:id="'list-lg-item-' + item.id"
v-for="item in items"
v-bind:key="item.id"
v-bind:class="itemClass(item)">
<td class="list-item-name">{{item.name}}</td>
<td class="list-included-parts">
<span v-for="part in item.parts" :key="part.id">{{part.name}}, </span>
</td>
</tr>
</tbody>
</table>
</div>
</template>
这是组件类(Typescript):
import { Component, Prop, Vue } from 'vue-property-decorator';
import { Item, Items } from '@/models/Item';
@Component
export default class ItemList extends Vue {
@Prop({required: false}) private items: Item[] = Items;
public itemClass(item: Item): any {
return {
'list-item-details': true,
'list-global-item': item.isGlobalItem(),
};
}
}
一切都相当简单,而且我可以看到代码是正确的:在运行时组件中相应的项目会突出显示。但是单元测试失败并显示消息
错误:[vue-test-utils]:find 没有返回 tr#list-lg-item-id.1,无法在空 Wrapper 上调用 classes()
这是我的测试(又是打字稿):
describe('ItemList.vue', () => {
const wrapper = shallowMount(ItemList, {
propsData: { items: Items },
});
it('highlights global items in the list', () => {
Items
.filter((i) => i.isGlobalItem())
.map((i) =>
// E.g. list-item-id.1
expect(wrapper.find(`tr#list-lg-item-${i.id}`).classes())
.to.contain('list-global-item'));
});
});
我只在 id 上尝试了 find()ing,而不是在该 id 上使用 tr,并看到了相同的效果。此外,如果我修改测试以从包装器中输出 HTML,我会看到输出中出现了正确设置 id 的 tr 元素。
<div data-v-63e8ee02="" id="item-list" class="item-list">
<table data-v-63e8ee02="" id="item-list-lg" class="table table-hover nomargin hidden-xs hidden-sm hidden-md">
<thead data-v-63e8ee02="">
<tr data-v-63e8ee02="">
<th data-v-63e8ee02="">Name</th>
<th data-v-63e8ee02="">Included parts</th>
</tr>
</thead>
<tbody data-v-63e8ee02="">
<tr data-v-63e8ee02="" id="list-item-id.1" class="list-item-details list-global-item">
<td data-v-63e8ee02="" class="list-item-name">Foo</td>
<td data-v-63e8ee02="" class="list-included-parts">
<span data-v-63e8ee02="">Bar, </span>
<span data-v-63e8ee02="">Baz, </span>
<span data-v-63e8ee02="">Qux, </span>
<span data-v-63e8ee02="">Quux, </span>
</td>
</tr>
</tbody>
</table>
</div>
我错过了什么?这与id 属性是动态设置的事实有关吗?
【问题讨论】:
-
项目列表会从位置 0 开始吗?因为您的测试中的错误消息是抱怨位置 1 是空的,这可能是真实/有效的..
标签: typescript vue.js vuejs2 vue-component