node:test
test()
test()
函数用于定义一个测试。它接收一个测试名称和一个异步函数作为参数。
const { test } = require('node:test');
const assert = require('node:assert');
test('example test', async (t) => {
assert.strictEqual(1 + 1, 2);
});
参数
name
:测试名称(可选)。fn
:测试函数,接收一个测试上下文对象t
。
describe()
describe()
函数用于将多个相关测试分组。它接收一个名称和一个函数作为参数。
const { describe, test } = require('node:test');
describe('Math operations', () => {
test('addition', (t) => {
assert.strictEqual(1 + 1, 2);
});
test('subtraction', (t) => {
assert.strictEqual(2 - 1, 1);
});
});
参数
name
:分组名称。fn
:包含测试的函数。
before()
, beforeEach()
, after()
, afterEach()
这些函数用于在测试之前或之后执行某些操作。
const { before, beforeEach, after, afterEach, test } = require('node:test');
const assert = require('node:assert');
before(() => {
console.log('Runs once before all tests');
});
beforeEach(() => {
console.log('Runs before each test');
});
after(() => {
console.log('Runs once after all tests');
});
afterEach(() => {
console.log('Runs after each test');
});
test('example test', (t) => {
assert.strictEqual(1 + 1, 2);
});
t.test()
在测试函数内部,可以使用 t.test()
创建子测试。
const { test } = require('node:test');
const assert = require('node:assert');
test('parent test', async (t) => {
await t.test('subtest 1', (t) => {
assert.strictEqual(1 + 1, 2);
});
await t.test('subtest 2', (t) => {
assert.strictEqual(2 + 2, 4);
});
});
t.skip()
, t.todo()
, t.only()
这些方法用于控制测试的执行。
t.skip()
:跳过当前测试或子测试。t.todo()
:标记未实现的测试。t.only()
:仅执行标记的测试,跳过其他测试。
const { test } = require('node:test');
const assert = require('node:assert');
test('skipped test', (t) => {
t.skip('this test will be skipped');
assert.strictEqual(1 + 1, 2);
});
test('todo test', (t) => {
t.todo();
});
test('only test', (t) => {
t.only();
assert.strictEqual(2 + 2, 4);
});
TestContext
测试上下文对象 t
提供了许多实用方法,用于控制测试行为和执行子测试。以下是一些常用方法:
t.diagnostic(msg)
:输出诊断消息。t.error(err, message)
:如果err
为真,则失败并输出message
。t.fail(message)
:显式失败并输出message
。t.pass(message)
:显式通过并输出message
。
const { test } = require('node:test');
const assert = require('node:assert');
test('example test with context', async (t) => {
t.diagnostic('Starting test');
try {
assert.strictEqual(1 + 1, 3);
} catch (err) {
t.error(err, 'Math is broken');
}
t.pass('Test completed');
});
t.plan(count)
plan(count)
方法用于指定期望的断言数量。如果断言数量不匹配,测试将失败。
const { test } = require('node:test');
const assert = require('node:assert');
test('planned test', async (t) => {
t.plan(2);
assert.strictEqual(1 + 1, 2);
assert.strictEqual(2 + 2, 4);
});