nuxt / test-utils

🧪 Test utilities for Nuxt
http://nuxt.com/docs/getting-started/testing
MIT License
287 stars 75 forks source link

vue-router mock #734

Closed tomsdob closed 5 months ago

tomsdob commented 5 months ago

Environment


Reproduction

https://stackblitz.com/edit/github-vy6psx

Describe the bug

Error: [vitest] Cannot mock "vue-router" because it is already loaded by "virtual:nuxt:/home/projects/github-vy6psx/.nuxt/vue-router-stub.mjs", "virtual:nuxt:/home/projects/github-vy6psx/.nuxt/pages.mjs".

Please, remove the import if you want static imports to be mocked, or clear module cache by calling "vi.resetModules()" before mocking if you are going to import the file again. See: https://vitest.dev/guide/common-errors.html#cannot-mock-mocked-file-js-because-it-is-already-loaded

I get this error message whenever I try to mock vue-router after upgrading to 3.9.0. Before the merge of nuxt-vitest and @nuxt/text-utils, the mock worked fine. I've tried to vi.resetModules() and other alike functions, but none of them have helped.

Additionally, if @nuxt/test-utils/module is present in nuxt.config.ts modules, npm run dev throws the following error:

This module cannot be imported in the Vue part of your app. [importing @nuxt/test-utils/runtime from pages/__tests__/index.spec.ts]

Additional context

Tests can be ran with npm run test. vi.mock() is located in pages/__tests__/index.spec.ts.

Logs

No response

aviv-adrianioanstefan commented 5 months ago

You can bypass this issue by creating a setup file for your tests and there you can add the mock for useRoute auto-import. But doing this will cause the following error:

TypeError: Cannot read properties of undefined (reading 'afterEach')
 ❯ node_modules/@nuxt/test-utils/dist/runtime/entry.mjs:7:14
      5|   const nuxtApp = useNuxtApp();
      6|   await nuxtApp.callHook("page:finish");
      7|   useRouter().afterEach(() => nuxtApp.callHook("page:finish"));
       |              ^
      8| }
      9| export {};

I've followed the instructions on the official documentation and nothing worked.

danielroe commented 5 months ago

The error is not thrown since https://github.com/nuxt/test-utils/pull/726, but note that setting a vue-router mock useRoute won't necessarily have the effect you want in a Nuxt app - as the auto-imported useRoute is actually a Nuxt utility that has slightly different (but more accurate) logic within a Nuxt app.

Instead you can do this:

  const wrapper = await mountSuspended(Index, {
    route: '/123'
  })