[READ-ONLY] Mirror of https://github.com/danielroe/nuxt-vitest. An vitest environment with support for testing code that needs a Nuxt runtime environment
nuxt nuxt-module testing unit-testing vitest
0

Configure Feed

Select the types of activity you want to include in your feed.

fix(vitest-environment-nuxt): register imports after context is created

Daniel Roe (Jun 1, 2023, 4:44 PM +0100) 434b39b0 867d73d4

+30 -25
+16
playground/tests/nuxt/mock-nuxt-composable-1.spec.ts
··· 1 + import { expect, it } from 'vitest' 2 + import { mockNuxtImport } from 'vitest-environment-nuxt/utils' 3 + 4 + mockNuxtImport('useRuntimeConfig', () => { 5 + return () => { 6 + return { 7 + public: { API_ENTRYPOINT: 'http://api.example.com' }, 8 + } 9 + } 10 + }) 11 + 12 + it('should mock core nuxt composables', () => { 13 + expect(useRuntimeConfig().public?.API_ENTRYPOINT).toMatchInlineSnapshot( 14 + '"http://api.example.com"' 15 + ) 16 + })
+10
playground/tests/nuxt/mock-nuxt-composable-2.spec.ts
··· 1 + import { expect, it } from 'vitest' 2 + import { mockNuxtImport } from 'vitest-environment-nuxt/utils' 3 + 4 + mockNuxtImport('useHead', () => { 5 + return () => true 6 + }) 7 + 8 + it('should mock core nuxt composables', () => { 9 + expect(useHead({})).toMatchInlineSnapshot('true') 10 + })
-16
playground/tests/nuxt/mock-nuxt-composable.spec.ts
··· 1 - import { expect, it } from 'vitest' 2 - import { mockNuxtImport } from 'vitest-environment-nuxt/utils' 3 - 4 - mockNuxtImport('useRuntimeConfig', () => { 5 - return () => { 6 - return { 7 - public: { API_ENTRYPOINT: 'http://api.example.com' }, 8 - } 9 - } 10 - }) 11 - 12 - it('should mock core nuxt composables', () => { 13 - expect(useRuntimeConfig().public?.API_ENTRYPOINT).toMatchInlineSnapshot( 14 - '"http://api.example.com"' 15 - ) 16 - })
+4 -9
packages/vitest-environment-nuxt/src/modules/mock.ts
··· 41 41 nuxt.hook('imports:extend', _ => { 42 42 imports = imports.concat(_) 43 43 }) 44 - nuxt.hook('imports:sources', _ => { 44 + nuxt.hook('imports:context', async ctx => { 45 45 // add core nuxt composables to imports 46 + const registeredImports = await ctx.getImports() 46 47 imports = imports.concat( 47 - // cast presets to imports 48 - _.filter(item => nuxtImportSources.includes(item.from)).flatMap(item => 49 - item.imports.map(name => ({ 50 - name: name, 51 - as: name, 52 - from: item.from, 53 - })) 54 - ) as Import[] 48 + registeredImports.filter(item => nuxtImportSources.includes(item.from)) 55 49 ) 56 50 }) 57 51 nuxt.hook('components:extend', _ => { ··· 131 125 const name = call.arguments[0].value as string 132 126 const importItem = imports.find(_ => name === (_.as || _.name)) 133 127 if (!importItem) { 128 + console.log({ imports }) 134 129 return this.error(`Cannot find import "${name}" to mock`) 135 130 } 136 131