본문 바로가기
Vue.js

[vue/test-utils] $route를 사용하는 컴포넌트 테스트 방법

by devebucks 2022. 7. 31.
728x90

다음처럼 설정을 해준다.

https://v1.test-utils.vuejs.org/guides/using-with-vue-router.html

 

Using with Vue Router | Vue Test Utils

Using with Vue Router Installing Vue Router in tests You should never install Vue Router on the Vue base constructor in tests. Installing Vue Router adds $route and $router as read-only properties on Vue prototype. To avoid this, we can create a localVue,

v1.test-utils.vuejs.org

 

 

에러가 발생한다.

console.error [vue-test-utils]: could not overwrite property $route, this is usually caused by a plugin that has added the property as a read-only value

 

 

해결방법

/**
 * @jest-environment jsdom
 */
import { shallowMount, createLocalVue } from '@vue/test-utils';
import Vuex from 'vuex';
import VueRouter from 'vue-router';
import Date from './Date.vue';

const localVue = createLocalVue();
localVue.use(Vuex);
const router = new VueRouter();

//🛠 아래처럼 코드를 작성하면 문제는 해결된다.
if (!process || process.env.NODE_ENV !== 'test') {
  localVue.use(VueRouter);
}

 

 

 

테스트를 할 컴포넌트의 test.js에서 사용할 라우터 설정

import { shallowMount, createLocalVue } from "@vue/test-utils";
import VueRouter from "vue-router";

const router = new VueRouter();
const $route = {
  name: "",
  query: {},
};

function makeWrapper() {
  return shallowMount(ClassMaterials, {
    localVue,
    propsData: {},
    router,
    mocks: {
      $route,
    },
  });
}
728x90

댓글