Nuxt.jsでテストを書いたらclient-onlyで詰まった【vue-test-utils】


はじめに

Nuxt.jsに触れ始めて1年ほど経ちますが最近初めてSSRを使いました。

そこで<client-only>タグを使うことがあったのですが、

console.error
      [Vue warn]: Unknown custom element: <client-only> - did you register the component correctly? For recursive components, make sure to provide the "name" option.

テストでエラーの山に遭遇しました。

原因

エラーに書いてある通り、<client-only>が登録されていないことが原因です。

vue-test-utilsはvueコンポーネントのテストを行うライブラリですが、<client-only>はNuxt固有のタグなのでそのままではエラーになってしまいます。

解決方法

<client-only>タグのスタブを作成します。

test/__mocks__/clientonlyMock.vue
<template>
  <span>
    <slot />
  </span>
</template>

<script>
export default {
}
</script>
util/jest.setup.js
import Vue from 'vue'
import { config } from '@vue/test-utils'
import clientonlyMock from '~/test/__mocks__/clientonlyMock.vue'

Vue.config.silent = true

// Mock Nuxt components
config.stubs['client-only'] = clientonlyMock

jest.config.jsに以下を追加

jest.config.js

  setupFiles: [
    '<rootDir>/util/jest.setup.js'
  ]

Nuxt.jsのissueでは"<span><slot/></span>"をスタブにする方法が紹介されていましたが、テキストでのスタブと見なされてワーニングが出てしまったので別ファイルで作成しています。

Enable Vue-Test-Utils to work with Nuxt · Issue #4115 · nuxt/nuxt.js
https://github.com/nuxt/nuxt.js/issues/4115

おわりに

SSRは色々なところに躓きがあって難しいです。

vue-test-utilsと少し仲良くなれた気がしてよかったです。

参考

マウンティングオプション | Vue Test Utils
https://vue-test-utils.vuejs.org/ja/api/options.html#stubs

Enable Vue-Test-Utils to work with Nuxt · Issue #4115 · nuxt/nuxt.js
https://github.com/nuxt/nuxt.js/issues/4115