Test plugin of useNuxtApp vitest
Hello all,
I don't know how to test one of my services I pass through useNuxtApp.
I use @nuxt/test-utils and my component got a
const { $someService } = useNuxtApp();
and in my test I want to mock it and try like this
I get this error :
[vitest] There was an error when mocking a module. If you are using "vi.mock" factory, make sure there are no top level variables inside, since this call is hoisted to top of the file
What am I doing wrong ?3 Replies
Hi @Ayho. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
Based on the knowledge sources provided, I can help you with your question about testing a service passed through
useNuxtApp
using Vitest in a Nuxt application.
The error you're encountering suggests that there might be an issue with how you're structuring your mock. Let's adjust your approach using the mockNuxtImport
function, which is specifically designed for mocking Nuxt's auto-import functionality in tests.
Here's a corrected version of your code that should work:
This approach is based on the example provided in the Nuxt documentation on Testing.
Key points to note:
1. We import mockNuxtImport
from '@nuxt/test-utils/runtime'.
2. We define useNuxtAppMock
as a simple mock function, without using vi.hoisted
.
3. We use mockNuxtImport
to mock the 'useNuxtApp' import, returning our mock function.
The error you were seeing ("There was an error when mocking a module...") typically occurs when there are top-level variables inside a vi.mock
call. By using mockNuxtImport
, we avoid this issue.
Remember that mockNuxtImport
can only be used once per mocked import per test file. If you need to provide different implementations between tests, you can use vi.hoisted
to create and expose your mocks, and then use those in mockNuxtImport
.
If you need more detailed information about mocking in Nuxt tests, I recommend checking the Nuxt documentation on Testing.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------<@372445754897203200> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
Tried this too but. I still get the
"There was an error when mocking a module. If you are using "vi.mock" factory, make sure there are no top level variables inside, since this call is hoisted to top of the file."
error