source

'vue-test-utils' 및 'jest'를 사용한 'Created' 후크를 사용한 테스트

goodcode 2022. 8. 17. 23:47
반응형

'vue-test-utils' 및 'jest'를 사용한 'Created' 후크를 사용한 테스트

다음과 같은 Vue 페이지가 있습니다.

<template>
</template>

<script>
created(){
    this.doSomething();
}

methods: {
    doSomething() {
        .....
    }
}

</script>

여기서 작성한 후크를 테스트하고 doSomething() 메서드가 호출되었는지 확인합니다.

이렇게 시도하면 농담도 패키지로 수입됩니다.json

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

const localVue = createLocalVue();

import Xyx from '/Xyx.vue';

const init = () => {
  wrapper = shallowMount(Xyx, { localVue });
  cmp = wrapper.vm;
};

describe('#created', () => {
  it('#doSomething', () => {
    init();
    wrapper.setMethods({
      doSomething: jest.fn(),
    })
    expect(cmp.doSomething).toHaveBeenCalled();
  });
});

이 작성한 후크의 유닛 테스트 케이스를 할 수 있습니까?

methods다음 중 v1에서 옵션이 더 이상 사용되지 않습니다.@vue/test-utils따라서 승인된 답변은 더 이상 작동하지 않습니다.저는 이 문제에 직접 부딪혔고, 이 문제를 어떻게 테스트할 수 있는지 알아보기 위해 출처를 조사하기로 결정했습니다.

Vue는 실제로 모든 후크를 저장해 놓은 것 같습니다.$options소유물.각 훅에는 기능 배열 옵션이 있습니다.문맥은 해당 함수에 구속되지 않으므로 다음 명령을 사용해야 합니다.call또는apply처형할 수 있습니다.

vm.$options.created.forEach(hook => {
  hook.call(vm);
});

당신의 메서드가 호출되어 있기 때문에created, 이것은, 모크를 설정하기 전에 실행됩니다.따라서, 당신의 테스트는 실패할 것입니다.
메서드를 초기화 시 모크로 대체해야 합니다(이 경우,shallowMount):

describe('Xyz', () => {
  it('should call doSomething() when created', () => {
    const doSomething = jest.fn()
    wrapper = shallowMount(Xyz, {
      localvue,
      methods: { doSomething }
    });
    expect(doSomething).toHaveBeenCalled();
  });
});

Sidenote: 선언하지 않습니다.cmp시험을 시작할 때, 당신은 시험 시작 시let cmp;


여기서도 비슷한 논의가 있습니다.링크된 코멘트 위에는 대부분의 Vue 컴포넌트 라이프 사이클 훅 속성을 시뮬레이션하는 방법이 있습니다.

테스트에서 필요할 때 후크를 호출할 수 있습니다.예를 들어 후크를 호출하기 전에 몇 가지 데이터를 조롱해야 하는 경우입니다.

import App from '@/App.vue';

// in test
App.created.call(wrapper.vm);

또한 Typescript에서는 vue-property-decorator를 사용하면 컴포넌트의 모양이 변경되므로 다음과 같이 수행해야 합니다.

App.extendOptions.created.call(wrapper.vm)

언급URL : https://stackoverflow.com/questions/56053163/testing-with-created-hook-with-vue-test-utils-and-jest

반응형