2022-04-15 15:19:05 +00:00
|
|
|
import { resolve } from 'node:path'
|
2023-01-30 12:09:48 +00:00
|
|
|
import { defu } from 'defu'
|
2022-02-11 13:22:58 +00:00
|
|
|
import type { TestContext, TestOptions, TestRunner } from './types'
|
|
|
|
|
2022-08-26 15:47:29 +00:00
|
|
|
let currentContext: TestContext | undefined
|
2022-02-11 13:22:58 +00:00
|
|
|
|
|
|
|
export function createTestContext (options: Partial<TestOptions>): TestContext {
|
|
|
|
const _options: Partial<TestOptions> = defu(options, {
|
|
|
|
testDir: resolve(process.cwd(), 'test'),
|
|
|
|
fixture: 'fixture',
|
|
|
|
configFile: 'nuxt.config',
|
2022-10-03 13:48:03 +00:00
|
|
|
setupTimeout: 120 * 1000,
|
2022-03-17 21:31:06 +00:00
|
|
|
dev: !!JSON.parse(process.env.NUXT_TEST_DEV || 'false'),
|
2022-02-16 21:34:32 +00:00
|
|
|
logLevel: 1,
|
2022-03-30 16:00:08 +00:00
|
|
|
server: true,
|
|
|
|
build: (options.browser !== false) || (options.server !== false),
|
2022-02-11 13:22:58 +00:00
|
|
|
nuxtConfig: {},
|
|
|
|
// TODO: auto detect based on process.env
|
|
|
|
runner: <TestRunner>'vitest',
|
|
|
|
browserOptions: {
|
2022-08-26 15:47:29 +00:00
|
|
|
type: 'chromium' as const
|
2022-02-11 13:22:58 +00:00
|
|
|
}
|
|
|
|
})
|
|
|
|
|
2022-09-05 08:51:00 +00:00
|
|
|
return setTestContext({
|
|
|
|
options: _options as TestOptions
|
|
|
|
})
|
2022-02-11 13:22:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export function useTestContext (): TestContext {
|
2022-11-10 14:55:47 +00:00
|
|
|
recoverContextFromEnv()
|
2022-02-11 13:22:58 +00:00
|
|
|
if (!currentContext) {
|
|
|
|
throw new Error('No context is available. (Forgot calling setup or createContext?)')
|
|
|
|
}
|
|
|
|
return currentContext
|
|
|
|
}
|
|
|
|
|
2022-08-26 15:47:29 +00:00
|
|
|
export function setTestContext (context: TestContext): TestContext
|
|
|
|
export function setTestContext (context?: TestContext): TestContext | undefined
|
|
|
|
export function setTestContext (context?: TestContext): TestContext | undefined {
|
2022-02-11 13:22:58 +00:00
|
|
|
currentContext = context
|
|
|
|
return currentContext
|
|
|
|
}
|
2022-03-17 21:31:06 +00:00
|
|
|
|
|
|
|
export function isDev () {
|
|
|
|
const ctx = useTestContext()
|
|
|
|
return ctx.options.dev
|
|
|
|
}
|
2022-11-10 14:55:47 +00:00
|
|
|
|
|
|
|
export function recoverContextFromEnv () {
|
|
|
|
if (!currentContext && process.env.NUXT_TEST_CONTEXT) {
|
|
|
|
setTestContext(JSON.parse(process.env.NUXT_TEST_CONTEXT || '{}'))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export function exposeContextToEnv () {
|
|
|
|
const { options, browser, url } = currentContext!
|
|
|
|
process.env.NUXT_TEST_CONTEXT = JSON.stringify({ options, browser, url })
|
|
|
|
}
|