diff --git a/vitest.base.unit.config.ts b/vitest.base.unit.config.ts index 890683f6..80094d9e 100644 --- a/vitest.base.unit.config.ts +++ b/vitest.base.unit.config.ts @@ -1,29 +1,6 @@ import path from "node:path"; import {defineConfig} from "vitest/config"; -import {BuiltinEnvironment} from "vitest/node"; -import {Environment} from "vitest/environments"; const __dirname = new URL(".", import.meta.url).pathname; -import denoEnvironment from "./vitest/environments/deno"; - -function getTestEnvironment( - runtime?: string -): BuiltinEnvironment | Environment { - switch (runtime) { - case "deno": - return denoEnvironment; - case "node": - return "node"; - default: { - if (runtime) { - throw new Error(`Unsupported JS Runtime '${runtime}'`); - } else { - throw new Error( - "Please define `JS_RUNTIME` env variable to either node | deno" - ); - } - } - } -} export default defineConfig({ resolve: { @@ -51,6 +28,6 @@ export default defineConfig({ "hanging-process", ], onConsoleLog: () => !process.env.TEST_QUIET_CONSOLE, - environment: getTestEnvironment(process.env.JS_RUNTIME), + globalSetup: [`${__dirname}/vitest/globalSetup/runtime.ts`], }, }); diff --git a/vitest/environments/deno.ts b/vitest/environments/deno.ts deleted file mode 100644 index 6d08c753..00000000 --- a/vitest/environments/deno.ts +++ /dev/null @@ -1,32 +0,0 @@ -import type {Environment} from "vitest/environments"; - -export default { - name: "deno", - transformMode: "ssr", - async setupVM() { - // @ts-expect-error - Ignore the global object - if (!global.Deno) { - throw new Error("Not valid deno runtime available"); - } - - // Deno supports `node:vm` module. - const vm = await import("node:vm"); - const context = vm.createContext(); - return { - getVmContext() { - return context; - }, - teardown() { - // called after all tests with this env have been run - }, - }; - }, - setup() { - // custom setup - return { - teardown() { - // called after all tests with this env have been run - }, - }; - }, -}; diff --git a/vitest/globalSetup/runtime.ts b/vitest/globalSetup/runtime.ts new file mode 100644 index 00000000..6715ad90 --- /dev/null +++ b/vitest/globalSetup/runtime.ts @@ -0,0 +1,33 @@ +import type { GlobalSetupContext } from "vitest/node"; + +export default function setup({ provide }: GlobalSetupContext): void { + const runtime = process.env.JS_RUNTIME; + + switch (runtime) { + case "deno": { + // @ts-expect-error - Ignore the global object + if (!global.Deno) { + throw new Error("Not valid deno runtime available"); + } + break; + } + case "node": { + if (!global.process) { + throw new Error("Not valid js runtime available"); + } + break; + } + default: + throw new Error( + `Not valid deno runtime available "${runtime}". Possible options are deno | node` + ); + } + + provide("runtime", runtime); +} + +declare module "vitest" { + export interface ProvidedContext { + runtime: "deno" | "node"; + } +}