programing

vue 2에서 구성 요소의 루트 요소에 대한 이벤트를 테스트하는 방법

prostudy 2022. 7. 2. 12:07
반응형

vue 2에서 구성 요소의 루트 요소에 대한 이벤트를 테스트하는 방법

다음 컴포넌트에 대한 유닛 테스트를 작성하고 있습니다.

<template>
  <sub-component
     @foo="bar"
  />
</template>
<script>
import SubComponent from './SubComponent';

export default {
  name: 'MyComponent',
  components: { SubComponent },
  methods: {
    bar(payload) {
       this.$emit('baz', ...payload);
    }
  }
}
</script>

테스트는 다음과 같습니다.

import { shallowMount } from '@vue/test-utils';
import _ from 'lodash';
import MyComponent from '../../components/MyComponent';

describe('MyComponent.vue', () => {
  let wrapper;

  beforeEach(() => {
    wrapper = shallowMount(MyComponent);
  });

  it('should emit baz on subcomponent foo', () => {
    const subComp = wrapper.find('sub-component-stub');
    expect(subComp.exists()).toBe(true);          // passes

    subComp.vm.$emit('foo');

    return wrapper.vm.$nextTick().then(() => {
      expect(wrapper.emitted().baz).toBeTruthy(); // does not pass;

      // upon logging: 
      console.log(_.isEqual(wrapper, subComp));   // => true 
    })
  })
})

이 예는 너무 단순하지만 원칙은 재사용이 가능해야 한다는 것입니다.<sub-component>(모달) 및 그 주변의 다양한 기능 래퍼(모달타입이 실행하는 특정 태스크와 관련된 것)는 추가 기능을 매핑합니다.부모 컴포넌트의 기능은 DRY에 위반되기 때문에 원하지 않습니다.특정 타입의 모달(modal)을 포함한 각 컴포넌트에 배치해야 합니다.

이렇게 하면 잘 될 거예요.<sub-component>의 직계가 아니었다<template>어쩐지 그런 것 같다.wrapper그리고.subComp는 같은 요소로 호스트 됩니다.

이것은 어떻게 적절하게 테스트해야 합니까?

또 다른 가능성은 돔에서 요소를 찾아 루트 성분의 방출 값을 확인하는 것입니다.

import { shallowMount } from '@vue/test-utils'
import MyComponent from './MyComponent.vue'
import SubComponent from './SubComponent.vue'

describe('MyComponent', () => {    

  it('should emit baz on subcomponent foo', () => {
    const wrapper = shallowMount(MyComponent)
    const subComponent = wrapper.find(SubComponent)

    expect(subComponent.exists()).toBe(true)
    expect(wrapper.emitted('baz')).toBeUndefined()

    subComponent.vm.$emit('foo', ['hello'])
    expect(wrapper.emitted('baz')[0]).toEqual(['hello'])
    // or expect(wrapper).toEmit('baz', 'hello') cf. below for toEmit
  })

})

Jest의 커스텀 매처를 원하는 경우:

toEmit(received, eventName, data) {
  if (data) {
    expect(received.emitted()[eventName][0]).toEqual([data])
  } else {
    expect(received.emitted()[eventName][0]).toEqual([])
  }
  return { pass: true }
} 

컴포넌트의 루트 요소에서 방출된 이벤트를 테스트하기 위해(및 양쪽을 호스트하는 루트 요소를 피하기 위해)subComp.vm그리고.wrapper.vm)에서 래퍼를 작성해야 합니다.wrapper.vm.$children[0]:

  it('should emit baz on subcomponent foo', () => {
    const subComp = createWrapper(wrapper.vm.$children[0]);
    expect(subComp.exists()).toBe(true);
    expect(wrapper.emitted().baz).toBeFalsy();

    subComp.vm.$emit('foo');

    return wrapper.vm.$nextTick().then(() => {
      expect(wrapper.emitted().baz).toBeTruthy();
    })
  })

언급URL : https://stackoverflow.com/questions/54790447/how-to-test-events-on-the-root-element-of-component-in-vue-2

반응형