如何测试 vue vuetify v-autocomplete

时间:2021-02-22 09:36:05

标签: vue.js jestjs vuetify.js vue-test-utils v-autocomplete

不知何故,我在测试过程中无法在 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。此外,使用 console.log(wrapper.html()) 打印 html 不会显示 v-autocomplete 的项目。所以我的问题是:

  1. 我如何测试物品是否已加载?
  2. 如何将加载的其中一个设置为 v-autocomplete 的选定项目?

1 个答案:

答案 0 :(得分: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