I'm having trouble creating a unit test for a Vue.js component where I need to check if a specific CSS class is added to the template.
Below is the template code:
<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>
Here's the Component class (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(),
};
}
}
The code looks correct as the items are properly highlighted in the component during runtime. However, the unit test fails with the following error message:
Error: [vue-test-utils]: find did not return tr#list-lg-item-id.1, cannot call classes() on empty Wrapper
This is my test code (Typescript):
describe('ItemList.vue', () => {
const wrapper = shallowMount(ItemList, {
propsData: { items: Items },
});
it('highlights global items in the list', () => {
Items
.filter((i) => i.isGlobalItem())
.map((i) =>
// For example, list-item-id.1
expect(wrapper.find(`tr#list-lg-item-${i.id}`).classes())
.to.contain('list-global-item'));
});
});
I have tried using find()
with just the id instead of a tr
element with that id without success. Additionally, when I output the HTML from the wrapper in the test, I can see that the tr
element with the correct id is present.
<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>
What could be causing this issue? Could it be related to the fact that the id
attribute is set dynamically?