5

I'm trying to setup vitest + @vue/test-utils but I can't test some components that use ref(Vue) or useCookie (Nuxt), I have the same problem with Pinia as well where I import globally 2 functions in the nuxt.config.js like this

[
  '@pinia/nuxt',
  {
    autoImports: ['defineStore', 'acceptHMRUpdate'],
  }
] 

This is my vitest.config.js setup:

import { defineConfig } from "vite"
import vue from "@vitejs/plugin-vue"
import AutoImport from 'unplugin-auto-import/vite'
import path from 'path'

export default defineConfig({
  plugins: [
    vue(),
    AutoImport({
      imports: ['vue'],
      dirs: ['./composables/']
    })
  ],
  test: {
    globals: true,
    environment: 'jsdom',
    coverage: {
      provider: 'c8',
      reporter: 'html',
      reportsDirectory: './coverage'
    },
  resolve: {
    alias: {
      '~': path.resolve(__dirname, './')
    }
  },
})

and the component I'm trying to test is something like this:

<script setup>
import AButton from '~/components/atoms/a-button/a-button.vue'
...

defineProps({
  label: {
    type: String,
    required: true
  },
})

const show = ref(false)

const Squad = useCookie('squad', { maxAge: 60 * 60 * 24 * 7 })
const appStore = useAppStore()

In Nuxt 3 as you know you don't import { ref } from vue or ... useCookie from.. they are auto-imported but vitest doesn't recognize them, I saw a couple of questions but none have an answer that solves my problem.

These are some:

Seba
  • 617
  • 1
  • 8
  • 33

1 Answers1

3

I had the same problem with refs and Nuxt 3 and I solved it by using unplugin-auto-import/vite

After installing, add the AutoImport configuration to the vitest.config.ts:

import vue from "@vitejs/plugin-vue";
import AutoImport from "unplugin-auto-import/vite";

export default {
  plugins: [
    vue(),
    AutoImport({
      imports: ["vue"],
    }),
  ],
  test: {
    globals: true,
    environment: "jsdom",
  },
  coverage: {
    all: true,
  },
};
Ana Robles
  • 31
  • 3
  • 1
    yes I managed to import vue stuff like you but I'm still unable to auto import Nuxt stuff – Seba Mar 06 '23 at 10:13
  • Hello, finally I found a solution for mocking the Nuxt auto imports in my test components. Here there's an example. https://medium.com/@ana.robles.developer/nuxt-3-vitest-vue-test-utils-mockear-en-los-test-funciones-auto-importadas-2242297eb06d – Ana Robles May 17 '23 at 20:02
  • mock everything doesn't really seem a robust solution, it solved it yes but not sure is the correct way. it would mean mock useRuntimeConfig or useCookie etc... – Seba May 17 '23 at 20:10