NuxtN
Nuxtβ€’11mo agoβ€’
5 replies
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);


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)

I just don't get why this isn't working... If anyone has already figured this out, please thank you πŸ˜…
Was this page helpful?