Open History to see the last commit
1// @vitest-environment node
2import { readFileSync } from 'node:fs'
3import { createContext, runInContext } from 'node:vm'
4import { transformSync } from 'esbuild'
5import { afterEach, describe, expect, it, vi } from 'vitest'
6import { shouldWarnInDevelopment } from '../src/development'
7
8const source = readFileSync(
9 new URL(`../src/development.ts`, import.meta.url),
10 `utf8`,
11)
12
13// Evaluates the module as a browser bundle would: `NODE_ENV` inlined by the
14// bundler, or left alone, and no `process` global.
15function inBrowser(
16 nodeEnv: string | undefined,
17 // Globals of the page, such as a `process` shim from another library.
18 globals: Record<string, unknown> = {},
19): (name: string) => boolean {
20 const { code } = transformSync(source, {
21 loader: `ts`,
22 format: `cjs`,
23 define:
24 nodeEnv === undefined
25 ? {}
26 : { 'process.env.NODE_ENV': JSON.stringify(nodeEnv) },
27 })
28 const bundle = { exports: {} as Record<string, unknown> }
29 runInContext(
30 code,
31 createContext({ ...globals, module: bundle, exports: bundle.exports }),
32 )
33 return bundle.exports.shouldWarnInDevelopment as (name: string) => boolean
34}
35
36describe(`development warnings`, () => {
37 afterEach(() => vi.unstubAllEnvs())
38
39 it(`warn in a browser development bundle without a process global`, () => {
40 expect(inBrowser(`development`)(`DISABLE`)).toBe(true)
41 })
42
43 it(`stay on when a page's process shim has no env`, () => {
44 expect(inBrowser(`development`, { process: {} })(`DISABLE`)).toBe(true)
45 })
46
47 it(`stay off in a browser production bundle or without a bundler`, () => {
48 expect(inBrowser(`production`)(`DISABLE`)).toBe(false)
49 expect(inBrowser(undefined)(`DISABLE`)).toBe(false)
50 })
51
52 it(`honor the disable variable and production under Node`, () => {
53 vi.stubEnv(`NODE_ENV`, `development`)
54 expect(shouldWarnInDevelopment(`DISABLE`)).toBe(true)
55 vi.stubEnv(`DISABLE`, `1`)
56 expect(shouldWarnInDevelopment(`DISABLE`)).toBe(false)
57 vi.unstubAllEnvs()
58 vi.stubEnv(`NODE_ENV`, `production`)
59 expect(shouldWarnInDevelopment(`DISABLE`)).toBe(false)
60 })
61})