0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Nuxt3のscript setupでオートインポートされるフックを使用しているコンポーネントでのVitestの書き方

Posted at

2022/11時点の情報です。
恐らく変わる可能性も高いと思われるので、暫定的な方法として。

Nuxt3で useRoute(), useRouter(), useRuntimeConfig() ... 等は、setup時にオートインポートされる。
これらが vitest 側で ReferenceError になってしまう問題の対策。

コンポーネント側

オートインポートされるものを、import { ... } from '#imports' のような形で、明示的に読み込む。

Sample.vue
<script setup lang="ts">
import {
  useRoute,
  useRouter,
  useRuntimeConfig,
  //...
} from '#imports' // 読み込む

const route = useRoute()
const router = useRouter()
const runtimeConfig = useRuntimeConfig()
// ...
</script>

<template>
  <div>...</div>
</template>

vitest.config.ts 側

vitest.config.ts 側で、aliasを設定する。

vitest.config.ts
/// <reference types="vitest" />

import path from 'path'
import { defineConfig } from 'vite'
import Vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [Vue()],
  test: {
    globals: true,
    environment: 'jsdom',
  },
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './'),
      '~': path.resolve(__dirname, './'),
      '#imports': path.resolve(__dirname, './.nuxt/imports.d.ts'), // 追加
    },
  },
})

テスト側

テスト側では vi.mock() でその値をモックすればOK。

Sample.spec.ts
vi.mock('#imports', () => {
  return {
    useRoute() {
      return {
        // ... 値をセット
      }
    },
    useRouter() {
      return {
        // ... 値をセット
      }
    },
    useRuntimeConfig() {
      return {
        // ... 値をセット
      }
    },
  }
})

参考

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?