不知何故,我无法在测试期间看到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
。打印 htmlconsole.log(wrapper.html())
也不会显示v-autocomplete
. 所以我的问题是:
- 如果物品已加载,我该如何测试?
- 如何将加载的一项设置为 的选定项
v-autocomplete
?