5

I am using Nuxt 3 on the current project at work. We just started writing tests (this is my first time doing that). I'm trying to test a component which has Nuxt useRouter and my basic test fails because useRouter is not recognized as a function. At first I was having trouble with the import being resolved. I changed nuxt/app import location to #imports as well as adding an alias to target the location of imports and that fixed the initial issue. My code looks something like this:

They way I'm importing the router:

import { useRouter } from '#imports'

vitest.config.js

import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vitest/config'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./', import.meta.url)),
      '#imports': './node_modules/nuxt/dist/pages/runtime/composables.mjs'
    }
  },
  test: {
    globals: true,
    environment: 'jsdom',
    coverage: {
      provider: 'c8',
      reporter: ['text', 'json', 'html']
    }
  }
})

The test itself:

import { describe, it, expect } from 'vitest'
import { mount } from '@vue/test-utils'

import AppNavbar from './AppNavbar.vue'

describe('AppNavbar', () => {
  const wrapper = mount(AppNavbar)

  it('renders', () => {
    expect(wrapper.vm).toBeTruthy()
  })
})

Fail message:

TypeError: useRouter is not a function

Am I doing something wrong? Is vue-test-utils even able to see Nuxt composables?

Thanks in advance!

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.