1

我有一个带有v-autocomplete. 它有select和的观察者search

// SearchTest.vue

<template>
  <v-autocomplete
    v-model="select"
    :items="items"
    :loading="isLoading"
    :search-input.sync="search"
    hide-no-data
    hide-selected
    placeholder="Type search query"
    return-object
  ></v-autocomplete>
</template>

<script>
export default {
  data: () => ({
    select: null,
    isLoading: false,
    search: null,
    items: [],
  }),
  watch: {
    select(val) {
      console.log('select: ', val);
    }
    search(val) {
      console.log('search: ', val);
    },
  },
};
</script>

<style></style>

我正在测试它如下。我希望两个观察者都应该开火。事实上,只有select观察者被解雇了。search观察者没有。

// SearchTest.spec.js

import { createLocalVue, mount } from '@vue/test-utils'
import SearchTest from '@/components/SearchTest.vue'

import Vue from 'vue'
import Vuetify from 'vuetify'

Vue.use(Vuetify)

describe('SearchTest.vue', () => {
  const localVue = createLocalVue();
  const vuetify = new Vuetify({});
  let spy;
  beforeAll(() => {
    spy = jest.spyOn(console, 'log');
  })

  afterEach(() => {
    spy.mockClear();
  })

  it('Select', () => {
    const wrapper = mount(SearchTest, { localVue, vuetify });

    // Triggers select.
    wrapper.vm.select = 'select';
    wrapper.vm.$nextTick(() => {
      expect(spy).toBeCalled();  // OK
    });
  })

  it('Search', () => {
    const wrapper = mount(SearchTest, { localVue, vuetify });

    // Should trigger search, but fails.
    wrapper.vm.search = 'search';
    wrapper.vm.$nextTick(() => {
      expect(spy).toBeCalled();  // Fail
    });
  })
})

Search有什么通过考试的想法吗?

4

1 回答 1

1

我不确切知道发生了什么,但我发现如果没有选择任何项目(source) ,v-autocomplete内部会将搜索属性设置为创建时。它是通过使用来实现的,我认为在测试中设置搜索值时会出现问题。我找到了两种缓解这种情况的方法:nullthis.$nextTick

1

search将变化和断言嵌套到另一个$nextTick似乎是诀窍。

it('Search', () => {
  const wrapper = mount(SearchTest, { localVue, vuetify });

  wrapper.vm.$nextTick(() => {
    wrapper.vm.search = 'search';
    wrapper.vm.$nextTick(() => {
      expect(spy).toBeCalled();
    });
  });
})

2

对于这个解决方案,我进行了初始化wrapper并将其放入beforeEach. 它的作用基本相同,但我猜组件的安装时间不同,所以它不会$nextTickv-autocomplete.

describe('SearchTest.vue', () => {
  const localVue = createLocalVue();
  const vuetify = new Vuetify({});
  let spy;
  let wrapper;

  beforeEach(() => {
    wrapper = mount(SearchTest, { localVue, vuetify });
  })

  beforeAll(() => {
    spy = jest.spyOn(console, 'log');
  })

  afterEach(() => {
    spy.mockClear();
  })

  it('Select', () => {
    // Triggers select.
    wrapper.vm.select = 'select';
    wrapper.vm.$nextTick(() => {
      expect(spy).toBeCalled();  // OK
    });
  })

  it('Search', () => {
    // Should trigger search, but fails.
    wrapper.vm.search = 'search';
    wrapper.vm.$nextTick(() => {
      expect(spy).toBeCalled();  // Fail
    });
  })
})
于 2021-03-30T14:25:36.573 回答