diff --git a/examples/app-vitest-full/tests/nuxt/mock-nuxt-composable-3.spec.ts b/examples/app-vitest-full/tests/nuxt/mock-nuxt-composable-3.spec.ts index 0a2fde714..5ecb88f4f 100644 --- a/examples/app-vitest-full/tests/nuxt/mock-nuxt-composable-3.spec.ts +++ b/examples/app-vitest-full/tests/nuxt/mock-nuxt-composable-3.spec.ts @@ -15,6 +15,8 @@ mockNuxtImport('useDefaultExport', () => { mockNuxtImport(add, () => mocks.add) +const useGlobalComponentMessageMock = mockNuxtImport('useGlobalComponentMessage', () => vi.fn(() => ({ message: 'mocked' }))) + it('should mock composables from project', () => { expect(useAutoImportedTarget()).toMatchInlineSnapshot('"mocked"') }) @@ -27,3 +29,10 @@ it('should mock composables with hoisted mocks', () => { expect(add(111, 222)).toBe(123) expect(mocks.add).toHaveBeenLastCalledWith(111, 222) }) + +it('should mock composables with returned mocks', () => { + expect(useGlobalComponentMessage().message).toBe('mocked') + useGlobalComponentMessageMock.mockReturnValueOnce({ message: 'changed' }) + expect(useGlobalComponentMessage().message).toBe('changed') + expect(useGlobalComponentMessageMock).toHaveBeenCalledTimes(2) +}) diff --git a/src/module/plugins/mock.ts b/src/module/plugins/mock.ts index 3042b2262..9fdee9743 100644 --- a/src/module/plugins/mock.ts +++ b/src/module/plugins/mock.ts @@ -133,7 +133,17 @@ export const createMockPlugin = (ctx: MockPluginContext) => createUnplugin(() => return this.error(`Cannot find import "${name}" to mock`) } - removeCallExpression(node.arguments[0]!, node.arguments[1]!) + if (isExpressionStatement(parent)) { + removeCallExpression(node.arguments[0]!, node.arguments[1]!) + } + else { + // the return value is used, so replace the call with a reference to the mock + s.overwrite( + node.start, + node.end, + `globalThis.${HELPER_MOCK_HOIST}[${JSON.stringify(importItem.from)}][${JSON.stringify(importItem.name)}]`, + ) + } mocksImport.push({ name, diff --git a/src/runtime-utils/mock.ts b/src/runtime-utils/mock.ts index 442384b96..482a724fd 100644 --- a/src/runtime-utils/mock.ts +++ b/src/runtime-utils/mock.ts @@ -107,6 +107,9 @@ export function registerEndpoint(url: string, options: EventHandler | { handler: } } +// eslint-disable-next-line @typescript-eslint/no-explicit-any +type MockNuxtImportTarget = T extends string ? any : T + /** * `mockNuxtImport` allows you to mock Nuxt's auto import functionality. * @param _target - name of an import to mock or mocked target. @@ -142,15 +145,23 @@ export function registerEndpoint(url: string, options: EventHandler | { handler: * (...args) => ({ ...vi.mocked(useRoute).getMockImplementation()!(...args), path: '/mocked' }), * ) * ``` + * @example + * ```ts + * // Using the returned mock + * const useStorageMock = mockNuxtImport('useStorage', () => vi.fn()) + * + * // Override in test + * useStorageMock.mockReturnValue({ value: 'mocked storage' }) + * + * // With a type parameter, pass the mock type as well to keep it in the return type + * const useRouteMock = mockNuxtImport>('useRoute', () => vi.fn()) + * ``` * @see https://nuxt.com/docs/getting-started/testing#mocknuxtimport */ -export function mockNuxtImport( +export function mockNuxtImport = MockNuxtImportTarget>( _target: string | T, - _factory: T extends string - // eslint-disable-next-line @typescript-eslint/no-explicit-any - ? (original: any) => any - : (original: T) => T | Promise, -): void { + _factory: (original: MockNuxtImportTarget) => R | Promise, +): R { throw new Error( 'mockNuxtImport() is a macro and it did not get transpiled. This may be an internal bug of @nuxt/test-utils.', ) diff --git a/test/types/mock-nuxt-import.test-d.ts b/test/types/mock-nuxt-import.test-d.ts index 1f1172867..fba66f69a 100644 --- a/test/types/mock-nuxt-import.test-d.ts +++ b/test/types/mock-nuxt-import.test-d.ts @@ -1,4 +1,5 @@ -import { describe, it, expectTypeOf } from 'vitest' +import { describe, it, expectTypeOf, vi } from 'vitest' +import type { Mock } from 'vitest' import { mockNuxtImport } from '@nuxt/test-utils/runtime' describe('mockNuxtImport', () => { @@ -82,4 +83,29 @@ describe('mockNuxtImport', () => { mockNuxtImport(useRoute, _ => () => ({})) }) }) + + describe('return value', () => { + it('returns the mock created by the factory', () => { + const mock = vi.fn(() => 'mocked') + expectTypeOf(mockNuxtImport('useRoute', () => mock)).toEqualTypeOf(mock) + expectTypeOf(mockNuxtImport('useRoute', original => original)).toEqualTypeOf() + expectTypeOf(mockNuxtImport(useRoute, original => vi.fn(original))).toEqualTypeOf>() + expectTypeOf(mockNuxtImport(useRoute, original => Promise.resolve(vi.fn(original)))).toEqualTypeOf>() + }) + + it('returns the mock with type parameters', () => { + // TypeScript cannot partially infer type arguments, so with only `T` given the return type is `T` + expectTypeOf(mockNuxtImport('useRoute', () => vi.fn())).toEqualTypeOf() + + const useRouteMock = mockNuxtImport>('useRoute', () => vi.fn()) + expectTypeOf(useRouteMock).toEqualTypeOf>() + expectTypeOf(useRouteMock.mockReturnValue).toBeFunction() + + expectTypeOf(mockNuxtImport>('useRoute', original => vi.fn(original))).toEqualTypeOf>() + expectTypeOf(mockNuxtImport>('useRoute', original => Promise.resolve(vi.fn(original)))).toEqualTypeOf>() + + // @ts-expect-error return type is not correct + mockNuxtImport>('useRoute', () => () => '') + }) + }) }) diff --git a/test/unit/mock-transform.spec.ts b/test/unit/mock-transform.spec.ts index 870bdf6ef..94a95c392 100644 --- a/test/unit/mock-transform.spec.ts +++ b/test/unit/mock-transform.spec.ts @@ -95,6 +95,20 @@ describe('mocking', () => { `)).toMatchInlineSnapshot(expected) }) + it('should replace the call with the mock when its return value is used', async () => { + pluginContext.imports = [{ + name: 'useSomeExport', + from: 'bob', + }] + const code = await getResult(` + import { mockNuxtImport } from '@nuxt/test-utils/runtime' + const useSomeExportMock = mockNuxtImport('useSomeExport', () => vi.fn()) + `) + expect(code).toContain('const useSomeExportMock = globalThis.__NUXT_VITEST_MOCKS["bob"]["useSomeExport"]') + expect(code).toContain('globalThis.__NUXT_VITEST_MOCKS["bob"]["useSomeExport"] = await (() => vi.fn())(') + expect(code).not.toContain('mockNuxtImport(') + }) + it('should not add `vi` import if it already exists', async () => { pluginContext.imports = [{ name: 'useSomeExport',