Тестирование с помощью обновленного хука с помощью vue-test-utils и jest - PullRequest
1 голос
/ 16 октября 2019

У меня есть код компонента vue, как показано ниже

updated: function() {
   // set showPackages = true after all the child component render
   this.$nextTick(function() {
      this.show = this.element.show ? true : false
      this.done = true
   })
}

Теперь мы хотим протестировать этот обновленный хук и проверить, установлен ли this.show.

У кого-нибудь естьЛюбая идея, как написать тестовые случаи для этого ловушки жизненного цикла?

1 Ответ

0 голосов
/ 16 октября 2019

Вы должны извлечь логику вашего update хука в отдельный метод:

  updated() {
    // set showPackages = true after all the child component render
    this.handleUpdate();
  },

  methods: {
    handleUpdate() {
      this.$nextTick(() => {
        this.show = this.element.show ? true : false;
        this.done = true;
      });
    }
  }

модульный тест :

import { createLocalVue, shallowMount } from '@vue/test-utils';
import YourComponent from '@/components/YourComponent';

const localVue = createLocalVue();

describe('YourComponent.vue', () => {

  test('async update lifecycle hook behavior', () => {
    const wrapper = shallowMount(YourComponent, {
      localVue,
      propsData: {
        element: {
          show: false
        },
        done: false,
        show: true
      }
    });
    expect(wrapper.exists()).toBe(true);
    expect(wrapper.vm.done).toBe(false);
    wrapper.vm.handleUpdate();
    wrapper.vm.$nextTick(() => {
      expect(wrapper.vm.done).toBe(true);
      expect(wrapper.vm.show).toBe(false);
    });
  });
});

См. Также:https://vue -test-utils.vuejs.org / guides / testing-async-components.html

Дополнительное предложение:

Вы можете еще больше улучшить свой код, заменив:

this.show = this.element.show ? true : false;

от

this.show = !!this.element.show;

(см. Также: https://eslint.org/docs/rules/no-unneeded-ternary)

...