Vue CLIでVuetify、TypeScript、テストランナーにJestを使ったら下記のようなエラーがたくさん出た。
/app # yarn test:unit
yarn run v1.21.1
$ vue-cli-service test:unit
PASS tests/unit/example.spec.ts (6.266s)
MainNavigation.vue
✓ mount navigation (55ms)
console.error node_modules/vue/dist/vue.runtime.common.dev.js:621
[Vue warn]: Unknown custom element: <v-navigation-drawer> - did you register the component correctly? For recursive components, make sure to provide the "name" option.
found in
---> <Anonymous>
<Root>
console.error node_modules/vue/dist/vue.runtime.common.dev.js:621
[Vue warn]: Unknown custom element: <v-list-item> - did you register the component correctly? For recursive components, make sure to provide the "name" option.
found inWarnなのでテスト自体はPASSするけど気持ち悪いので直したい。
もちろん、yarn serveした場合は上記のエラーもなく、ページを正常に表示できている。
そういえば、下記のような記述を見たのでこれかと思った。
vue-jest は現在、カスタムブロックのサポートやスタイルのロードなど、vue-loader のすべての機能をサポートしていません。さらに、コード分割などの Webpack 固有の機能はサポートされていません。サポートされていない機能を使用するには、 Jest の代わりに Mocha をテストランナーとして使用します。
Mochaを使えというけど、Jestの方が流行ってるっぽいから使いたい。
setup.jsの作成
検索したらVuetifyの公式ドキュメントが見つかった。
これ通り、Vue CLIでできたtests/unit/配下にsetup.jsを設置した
// tests/unit/setup.js import Vue from 'vue' import Vuetify from 'vuetify' Vue.use(Vuetify)
もちろんこのままでは読み込まれない。
Jestの設定
上記のファイルをどうやってJestで読み込ませるか調べるとsetupFilesというまんまなオプションが見つかった。
これをVue CLIでインストール時にできたjest.config.jsに追加する。
// jest.config.js
module.exports = {
preset: '@vue/cli-plugin-unit-jest/presets/typescript-and-babel',
setupFiles: ['./tests/unit/setup.js']
}無事成功した。
# yarn test:unit
yarn run v1.21.1
$ vue-cli-service test:unit
PASS tests/unit/example.spec.ts (5.879s)
MainNavigation.vue
✓ mount navigation (45ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 12.386s
Ran all test suites.
Done in 45.24s.
setupFilesのパスは相対パスじゃないとだめ?
パスは'tests/unit/setup.js'にしてしまうとモジュールを探してしまうようで、エラーになるので相対パスにした。
$ vue-cli-service test:unit
● Validation Error:
Module tests/unit/setup.js in the setupFiles option was not found.
<rootDir> is: /app
Configuration Documentation:
https://jestjs.io/docs/configuration.html
- 作者:Boris Cherny
- 出版社/メーカー: オライリージャパン
- 発売日: 2020/03/16
- メディア: 単行本(ソフトカバー)