Skip to content
This repository has been archived by the owner on Apr 6, 2023. It is now read-only.

feat(test-utils): allow mounting single component for testing #5723

Merged
merged 11 commits into from
Apr 6, 2023
Merged
5 changes: 5 additions & 0 deletions packages/nuxt/src/app/components/nuxt-root.vue
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
<Suspense @resolve="onResolve">
<ErrorComponent v-if="error" :error="error" />
<IslandRenderer v-else-if="islandContext" :context="islandContext" />
<component :is="SingleRenderer" v-else-if="SingleRenderer" />
<AppComponent v-else />
</Suspense>
</template>
Expand All @@ -21,6 +22,10 @@ const IslandRenderer = process.server
const nuxtApp = useNuxtApp()
const onResolve = nuxtApp.deferHydration()

const url = process.server ? nuxtApp.ssrContext.url : window.location.pathname
const SingleRenderer = process.dev && process.server && url.startsWith('/__nuxt_component_test__/') && defineAsyncComponent(() => import('#build/test-component-wrapper.mjs')
.then(r => r.default(process.server ? url : window.location.href)))

// Inject default route (outside of pages) as active route
provide('_route', useRoute())

Expand Down
19 changes: 19 additions & 0 deletions packages/nuxt/src/app/components/test-component-wrapper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { parseURL } from 'ufo'
import { defineComponent, h } from 'vue'
import { parseQuery } from 'vue-router'

export default (url:string) => defineComponent({
name: 'NuxtTestComponentWrapper',

async setup (props, { attrs }) {
const query = parseQuery(parseURL(url).search)
const urlProps = query.props ? JSON.parse(query.props as string) : {}
const comp = await import(/* @vite-ignore */ query.path as string).then(r => r.default)
return () => [
h('div', 'Component Test Wrapper for ' + query.path),
h('div', { id: 'nuxt-component-root' }, [
h(comp, { ...attrs, ...props, ...urlProps })
])
]
}
})
5 changes: 5 additions & 0 deletions packages/nuxt/src/core/templates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ export const errorComponentTemplate: NuxtTemplate<TemplateContext> = {
filename: 'error-component.mjs',
getContents: ctx => genExport(ctx.app.errorComponent!, ['default'])
}
// TODO: Use an alias
export const testComponentWrapperTemplate = {
filename: 'test-component-wrapper.mjs',
getContents: (ctx: TemplateContext) => genExport(resolve(ctx.nuxt.options.appDir, 'components/test-component-wrapper'), ['default'])
}

export const cssTemplate: NuxtTemplate<TemplateContext> = {
filename: 'css.mjs',
Expand Down
1 change: 1 addition & 0 deletions packages/test-utils/build.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export default defineBuildConfig({
declaration: true,
entries: [
'src/index',
'src/experimental',
{ input: 'src/runtime/', outDir: 'dist/runtime', format: 'esm' }
],
externals: [
Expand Down
1 change: 1 addition & 0 deletions packages/test-utils/experimental.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './dist/experimental'
7 changes: 6 additions & 1 deletion packages/test-utils/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs"
},
"./experimental": {
"types": "./dist/experimental.d.ts",
"import": "./dist/experimental.mjs"
}
},
"files": [
Expand All @@ -26,7 +30,8 @@
"get-port-please": "^3.0.1",
"jiti": "^1.18.2",
"ofetch": "^1.0.1",
"pathe": "^1.1.0"
"pathe": "^1.1.0",
"ufo": "^1.1.1"
},
"devDependencies": {
"playwright": "^1.32.2",
Expand Down
23 changes: 23 additions & 0 deletions packages/test-utils/src/experimental.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { fetch as _fetch, $fetch as _$fetch } from 'ofetch'
import * as _kit from '@nuxt/kit'
import { resolve } from 'pathe'
import { stringifyQuery } from 'ufo'
import { useTestContext } from './context'
import { $fetch } from './server'

/**
* This is a function to render a component directly with the Nuxt server.
*/
export function $fetchComponent (filepath: string, props?: Record<string, any>) {
return $fetch(componentTestUrl(filepath, props))
}

export function componentTestUrl (filepath: string, props?: Record<string, any>) {
const ctx = useTestContext()
filepath = resolve(ctx.options.rootDir, filepath)
const path = stringifyQuery({
path: filepath,
props: JSON.stringify(props)
})
return `/__nuxt_component_test__/?${path}`
}
5 changes: 4 additions & 1 deletion packages/test-utils/src/server.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { resolve } from 'node:path'
import { execa } from 'execa'
import { getRandomPort, waitForPort } from 'get-port-please'
import type { FetchOptions } from 'ofetch'
import { fetch as _fetch, $fetch as _$fetch } from 'ofetch'
import * as _kit from '@nuxt/kit'
import { resolve } from 'pathe'
import { useTestContext } from './context'

// @ts-ignore type cast
Expand Down Expand Up @@ -75,5 +75,8 @@ export function url (path: string) {
if (!ctx.url) {
throw new Error('url is not available (is server option enabled?)')
}
if (path.startsWith(ctx.url)) {
return path
}
return ctx.url + path
}
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 11 additions & 0 deletions test/basic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { setup, fetch, $fetch, startServer, isDev, createPage, url } from '@nuxt

import type { NuxtIslandResponse } from '../packages/nuxt/src/core/runtime/nitro/renderer'
import { expectNoClientErrors, expectWithPolling, renderPage, withLogs } from './utils'
import { $fetchComponent } from '@nuxt/test-utils/experimental'

const isWebpack = process.env.TEST_BUILDER === 'webpack'

Expand Down Expand Up @@ -1277,3 +1278,13 @@ describe.skipIf(isWindows)('useAsyncData', () => {
await expectNoClientErrors('/useAsyncData/promise-all')
})
})

describe.runIf(isDev())('component testing', () => {
it('should work', async () => {
const comp1 = await $fetchComponent('components/SugarCounter.vue', { multiplier: 2 })
expect(comp1).toContain('12 x 2 = 24')

const comp2 = await $fetchComponent('components/SugarCounter.vue', { multiplier: 4 })
expect(comp2).toContain('12 x 4 = 48')
})
})
1 change: 1 addition & 0 deletions vitest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export default defineConfig({
resolve: {
alias: {
'#app': resolve('./packages/nuxt/dist/app/index'),
'@nuxt/test-utils/experimental': resolve('./packages/test-utils/src/experimental.ts'),
'@nuxt/test-utils': resolve('./packages/test-utils/src/index.ts')
}
},
Expand Down