2

不知何故,我无法在测试期间看到html 内部itemsv-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. 所以我的问题是:

  1. 如果物品已加载,我该如何测试?
  2. 如何将加载的一项设置为 的选定项v-autocomplete
4

1 回答 1

0

您可以单击打开自动完成菜单.v-input__slot。我不认为,测试库功能是最佳实践。

单元测试:

it("should load the items", async () => {
  wrapper = mount(VAutocomplete, {
    localVue,
    vuetify,
    propsData: {}
  });

  const autocomplete = wrapper.element;
  const autocompleteControls = autocomplete.find(".v-input__slot");

  autocompleteControls.trigger("click");
  await wrapper.vm.$nextTick();

  expect(getItemsSpy).toBeCalledTimes(1);
  for (const item of items) {
    expect(getByText(wrapper.element, item.name)).toBeTruthy();
  }
});

来源: https ://github.com/vuetifyjs/vuetify/blob/master/packages/vuetify/src/components/VSelect/\_\_tests__/VSelect.spec.ts

于 2021-02-25T17:13:26.893 回答