N
Nuxt2mo ago
Melio.

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 :
const { useLazyFetchMock } = vi.hoisted(() => {
return {
useLazyFetchMock: vi.fn((): Promise<RecipeFetchResult> =>
Promise.resolve({ // default empty
status: "success",
error: null,
data: null,
}),
),
};
});
mockNuxtImport("useLazyFetch", () => useLazyFetchMock);
const { useLazyFetchMock } = vi.hoisted(() => {
return {
useLazyFetchMock: vi.fn((): Promise<RecipeFetchResult> =>
Promise.resolve({ // default empty
status: "success",
error: null,
data: null,
}),
),
};
});
mockNuxtImport("useLazyFetch", () => useLazyFetchMock);
I get this error :
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. Read more: https://vitest.dev/api/vi.html#vi-mock
at ManualMockedModule.resolve (file:///C:/Users/antoi/Documents/DEV/MES%20PROJETS%20GITHUB/nuxt-recipesmaster/node_modules/@vitest/mocker/dist/chunk-registry.js:146:27)
at processTicksAndRejections (node:internal/process/task_queues:95:5)
at VitestMocker.callFunctionMock (file:///C:/Users/antoi/Documents/DEV/MES%20PROJETS%20GITHUB/nuxt-recipesmaster/node_modules/vitest/dist/chunks/execute.PoofJYS5.js:388:21)
at VitestMocker.requestWithMock (file:///C:/Users/antoi/Documents/DEV/MES%20PROJETS%20GITHUB/nuxt-recipesmaster/node_modules/vitest/dist/chunks/execute.PoofJYS5.js:525:16)
at VitestExecutor.dependencyRequest (file:///C:/Users/antoi/Documents/DEV/MES%20PROJETS%20GITHUB/nuxt-recipesmaster/node_modules/vitest/dist/chunks/execute.PoofJYS5.js:803:20)
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. Read more: https://vitest.dev/api/vi.html#vi-mock
at ManualMockedModule.resolve (file:///C:/Users/antoi/Documents/DEV/MES%20PROJETS%20GITHUB/nuxt-recipesmaster/node_modules/@vitest/mocker/dist/chunk-registry.js:146:27)
at processTicksAndRejections (node:internal/process/task_queues:95:5)
at VitestMocker.callFunctionMock (file:///C:/Users/antoi/Documents/DEV/MES%20PROJETS%20GITHUB/nuxt-recipesmaster/node_modules/vitest/dist/chunks/execute.PoofJYS5.js:388:21)
at VitestMocker.requestWithMock (file:///C:/Users/antoi/Documents/DEV/MES%20PROJETS%20GITHUB/nuxt-recipesmaster/node_modules/vitest/dist/chunks/execute.PoofJYS5.js:525:16)
at VitestExecutor.dependencyRequest (file:///C:/Users/antoi/Documents/DEV/MES%20PROJETS%20GITHUB/nuxt-recipesmaster/node_modules/vitest/dist/chunks/execute.PoofJYS5.js:803:20)
I just don't get why this isn't working... If anyone has already figured this out, please thank you 😅
3 Replies
kapa.ai
kapa.ai2mo ago
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:
mockNuxtImport can only be used once per mocked import per test file. It is actually a macro that gets transformed to vi.mock and vi.mock is hoisted, as described here.
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:
import { vi } from 'vitest'
import { mockNuxtImport } from '@nuxt/test-utils/runtime'

const { useLazyFetchMock } = vi.hoisted(() => {
return {
useLazyFetchMock: vi.fn(() => {
return Promise.resolve({
status: "success",
error: null,
data: null,
})
})
}
})

mockNuxtImport('useLazyFetch', () => useLazyFetchMock)

// Then, inside your tests you can change the implementation:
// useLazyFetchMock.mockImplementation(() => {...})
import { vi } from 'vitest'
import { mockNuxtImport } from '@nuxt/test-utils/runtime'

const { useLazyFetchMock } = vi.hoisted(() => {
return {
useLazyFetchMock: vi.fn(() => {
return Promise.resolve({
status: "success",
error: null,
data: null,
})
})
}
})

mockNuxtImport('useLazyFetch', () => useLazyFetchMock)

// Then, inside your tests you can change the implementation:
// useLazyFetchMock.mockImplementation(() => {...})
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 importing 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:
beforeEach(() => {
useLazyFetchMock.mockClear()
})
test('test with default data', async () => {
// Uses the default mock implementation
})

test('test with custom data', async () => {
useLazyFetchMock.mockImplementation(() =>
Promise.resolve({
status: "success",
error: null,
data: { /* your test data */ }
})
)
// Your test code
})
beforeEach(() => {
useLazyFetchMock.mockClear()
})
test('test with default data', async () => {
// Uses the default mock implementation
})

test('test with custom data', async () => {
useLazyFetchMock.mockImplementation(() =>
Promise.resolve({
status: "success",
error: null,
data: { /* your test data */ }
})
)
// Your test code
})
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: ----------------------
kapa.ai
kapa.ai2mo ago
<@290467364372480000> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
Melio.
Melio.OP2mo ago
(kapa's answer isn't fixing my problem)

Did you find this page helpful?