jest+vue-test-utils tips
コンポーネントへのvue-router適用
createLocalVue 使う
code: javascript
import { createLocalVue, mount} from '@vue/test-utils';
import VueRouter from 'vue-router'
import Hoge from 'Hoge.vue';
const localVue = createLocalVue();
localVue.use(VueRouter);
const wrapper = mount(Hoge, { createLocalVue, router });
componentのmount/shallowMountでエラーになる記述
1. グローバル定数の直接参照
code: javascript
<template>
<!-- 略 -->
</template>
<script>
export default {
data() {
return { hoge } // hoge is not defined的なエラーでる
}
}
</script>
2. location.pathname
3. DOM操作(document.getElementById(...)など
上記の解決策の一つとしては、1~3のような記述は computed で記述するようにし、mount時に後述の方法で上書きする
その他のオプション上書き
mount の第二引数にマウンティングオプション以外のオプションを設定すると、上書きされる
computed : 上書き可
methods : 上書きするとワーニングでる
code: text
vue-test-utils: overwriting methods via the methods property is deprecated and will be removed in the next major version. There is no clear migration path for the methods property - ... code: javascript
// コンポーネント側
<template>
<!-- 例 -->
</template>
<script>
export default {
computed: {
huga() {
return 'huga';
}
},
methods: {
foo() {
return 'foo';
}
}
}
</script>
code: javascript
// テストコード側 mountの例
import { mount } from '@vue-test-utils';
import Hoge from 'Hoge.vue';
wrapper = mount(Hoge, {
computed: {
huga() {
return 'hugaaaa'; // hugaの返り値は'hugaaaa'になる
}
},
methods: {
foo() {
return 'fooooo'; // fooの返り値は'fooooo'になる ワーニングでるし非推奨
}
}
});