Warning
Deprecated repository
This repository is deprecated and will no longer receive updates or support. As of January > 25, 2024, i recommend using the following repository instead:
In-source testing with the Node.js Test Runner
Node.js >=18.0.0
npm i -D \
test-runner-register \
@swc-node/register \
@types/node \
typescript
path/to/script.ts:
const assert = require("node:assert/strict")
const { test, describe } = require("node:test")
if (
process.env.NODE_ENV === "test" &&
process.env.TEST_RUNNER_FILE === __filename
) {
// You can also use `testRunner` instead of "node:*" modules.
// const { test, assert, describe } = testRunner
describe("...", () => {
test("...", () => {
assert(true)
})
})
}
Run:
node -r test-runner-register \
-r @swc-node/register \
path/to/script.ts
Log:
▶ ...
✔ ... (0.195722ms)
▶ ... (0.838251ms)
ℹ tests 1
ℹ suites 1
ℹ pass 1
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 0.066372
package.json:
{
"type": "module"
}
path/to/script.ts:
import assert from "node:assert/strict"
import { test, describe } from "node:test"
if (
process.env.NODE_ENV === "test" &&
process.env.TEST_RUNNER_FILE === import.meta.url
) {
// You can also use `testRunner` instead of "node:*" modules.
// const { test, assert, describe } = testRunner
describe("...", () => {
test("...", () => {
assert(true)
})
})
}
Run (Node.js < 20.6.0):
node -r test-runner-register \
--loader @swc-node/register/esm \
./main.ts
Run (Node.js >= 20.6.0):
node --import test-runner-register/import \
./main.ts
Log:
▶ ...
✔ ... (0.153848ms)
▶ ... (0.78856ms)
ℹ tests 1
ℹ suites 1
ℹ pass 1
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 0.062858
test-runner-register
exports testRunner
global variable:
const test = require("node:test");
const assert = require("node:assert/strict");
global.testRunner = Object.assign(test, { assert });
env.d.ts:
/// <reference types="test-runner-register/globals" />
tsconfig.json:
{
"files": [
"./env.d.ts"
]
}
path/to/script.ts:
// import assert from "node:assert/strict"
// import { test, describe } from "node:test"
if (
process.env.NODE_ENV === "test" &&
process.env.TEST_RUNNER_FILE === import.meta.url
) {
// 🎉 You can also use `testRunner` instead of "node:*" modules.
const { test, assert, describe } = testRunner
describe("...", () => {
test("...", () => {
assert(true)
})
})
}