Skip to content

Commit b90c61e

Browse files
authored
feat(vitest-environment): add support for in-source testing (#651)
1 parent 648f4b6 commit b90c61e

File tree

4 files changed

+23
-1
lines changed

4 files changed

+23
-1
lines changed
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
export const add = (...args: number[]) => {
2+
return args.reduce((a, b) => a + b, 0)
3+
}

examples/app-vitest-full/pages/index.vue

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,16 @@
22
<div>Index page</div>
33
</template>
44

5-
<script setup>
5+
<script lang="ts">
66
definePageMeta({
77
value: 'set in index',
88
})
9+
if (import.meta.vitest) {
10+
const { it, expect } = import.meta.vitest
11+
it('add', () => {
12+
expect(add()).toBe(0)
13+
expect(add(1)).toBe(1)
14+
expect(add(1, 2, 3)).toBe(6)
15+
})
16+
}
917
</script>

examples/app-vitest-full/vitest.config.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ export default defineVitestConfig({
77
coverage: {
88
reportsDirectory: 'coverage',
99
},
10+
includeSource: ['../pages/index.vue'],
1011
environmentOptions: {
1112
nuxt: {
1213
rootDir: fileURLToPath(new URL('./', import.meta.url)),

src/module.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,16 @@ export default defineNuxtModule<NuxtVitestOptions>({
4545
rootStubPath: await resolvePath(resolver.resolve('./runtime/nuxt-root')),
4646
}))
4747

48+
// Support for in-source testing
49+
if (!nuxt.options.test && !nuxt.options.dev) {
50+
nuxt.options.vite.define ||= {}
51+
nuxt.options.vite.define['import.meta.vitest'] = 'undefined'
52+
}
53+
54+
nuxt.hook('prepare:types', ({ references }) => {
55+
references.push({ types: 'vitest/import-meta' })
56+
})
57+
4858
if (!nuxt.options.dev) return
4959

5060
// the nuxt instance is used by a standalone Vitest env, we skip this module

0 commit comments

Comments
 (0)