Multiple mockNuxtImport
Hi !
I'm using
mockNuxtImport
from @nuxt/test-utils/runtime to mock the useLazyFetch method, which works fine.
As mentioned in the documentation, we can't use multiple mockNuxtImport
as it'll be hoisted but we can use vi.hoisted
to expose mocks and use them in a single mockNuxtImport
use.
Thus, in order to get different results between tests, i'm trying to use it that way (RecipeFetchResult
just being a TypeScript interface) at the top of my test file :
I get this error :
I just don't get why this isn't working... If anyone has already figured this out, please thank you 😅3 Replies
Hi @Melio.. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
I understand you're having issues with using
mockNuxtImport
in your Nuxt tests. This is a common challenge when working with Nuxt's testing utilities.
The error you're encountering is related to how vi.mock
(which mockNuxtImport
uses under the hood) hoists the mocks to the top of the file. According to the documentation, mockNuxtImport
is actually a macro that gets transformed to vi.mock
, and as noted:
Nuxt Documentation - mockNuxtImport Looking at your code, the approach is generally correct, but there might be an issue with how you're structuring the mock. Here's a corrected example based on the documentation: A few things to check: 1. Make sure you're not using any top-level variables inside the hoisted function (as the error suggests) 2. Ensure you're importingmockNuxtImport
can only be used once per mocked import per test file. It is actually a macro that gets transformed tovi.mock
andvi.mock
is hoisted, as described here.
vi
from 'vitest'
3. Remember to restore mocks between tests to avoid state leakage
For different test cases, you can change the implementation within each test:
If you're still encountering issues, you might want to check if there are any TypeScript-related problems or if your RecipeFetchResult interface is causing complications.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------<@290467364372480000> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
(kapa's answer isn't fixing my problem)