isRunningInTest()
isRunningInTest() returns true when the code looks like it runs under a test runner.
Signature
Section titled “Signature”function isRunningInTest(): booleanParameters
Section titled “Parameters”None.
Behavior
Section titled “Behavior”It returns true when the first of these checks passes, in this order:
globalThis.windowis not set, as in Node.js.globalThis.EdgeRuntimeis set.- Vitest’s
__vitest_browser__or__vitest_worker__global is set. window.navigator.userAgentcontainsStorybookTestRunner,jsdom,HappyDOM, orHeadlessChrome.
Otherwise it returns false.
Edge cases:
- Any context without
windowcounts as a test. It returnstruein every Node.js process, not only test runs. - In a regular desktop browser, it returns
falseunless one of the globals above is set. - In a headless Chrome session that is not a test, it returns
true, because the user agent containsHeadlessChrome.
Use it in code that runs in a browser, such as a Storybook story, to tell a test run from a person viewing the page.
Examples
Section titled “Examples”Under Vitest, in Node.js and in Vitest browser mode (both covered by the package’s tests):
import { isRunningInTest } from '@repobuddy/test'import { expect, it } from 'vitest'
it('detects the code is running in test runner directly', () => { expect(isRunningInTest()).toBe(true)})Outside any test runner, in a plain Node.js script, it still returns true, because there is no window:
// check.mjs, run with `node check.mjs`import { isRunningInTest } from '@repobuddy/test'
console.log(isRunningInTest()) // trueWith a window whose user agent is a regular Chrome string, and none of the globals set, it returns false.