【发布时间】:2021-05-24 13:03:27
【问题描述】:
不知何故,在测试期间我无法在 html 中看到 items 的 v-autocomplete 并且设置项目也不起作用。在v-autocomplete(正在加载挂载的项目)和测试下方。
// v-autocomplete.vue
<template>
<v-autocomplete
:items="items"
item-text="name"
item-value="id"
></v-autocomplete>
</template>
<script>
export default {
data() {
return {
items: [],
};
},
mounted() {
service.getItems().then((response) => {
this.items = response;
});
},
};
</script>
测试看起来像这样:
//v-autocomplete.spec.js
import Vue from 'vue';
import Vuetify from 'vuetify';
import VAutocomplete from '@/components/v-autocomplete.vue';
import '@testing-library/jest-dom';
import { createLocalVue, mount } from '@vue/test-utils';
import service from '@/service/service';
Vue.use(Vuetify);
const items= [
{ name: 'Item 1', id: 1 },
{ name: 'Item 2', id: 2 },
];
const getItemsSpy = jest
.spyOn(service, 'getItems')
.mockImplementation(() => {
return new Promise((resolve) => {
resolve(items);
});
});
describe('v-autocomplete.vue', () => {
let localVue;
let vuetify;
let wrapper;
beforeEach(() => {
jest.clearAllMocks();
localVue = createLocalVue();
vuetify = new Vuetify();
});
it('should load the items', async () => {
wrapper = mount(VAutocomplete, {
localVue,
vuetify,
propsData: {},
});
expect(getItemsSpy).toBeCalledTimes(1);
for (const item of items) {
expect(getByText(wrapper.element, item.name)).toBeTruthy(); // Will fail -> Unable to find an element with the text
}
});
});
测试expect(getByText(wrapper.element, item.name)).toBeTruthy(); 将失败并显示消息Unable to find an element with the text。同样使用console.log(wrapper.html()) 打印html 不会显示v-autocomplete 的项目。所以我的问题是:
- 如果项目已加载,我该如何测试?
- 如何将已加载的一项设置为
v-autocomplete的选定项?
【问题讨论】:
标签: vue.js jestjs vuetify.js vue-test-utils v-autocomplete