context.plan(count[,options])
此函数用于设置测试中预期运行的断言和子测试的数量。如果实际运行的断言和子测试数量与预期数量不符,测试将会失败。
【This function is used to set the number of assertions and subtests that are expected to run within the test. If the number of assertions and subtests that run does not match the expected count, the test will fail.】
注意:为了确保断言被跟踪,必须使用
t.assert,而不能直接使用assert。
test('top level test', (t) => {
t.plan(2);
t.assert.ok('some relevant assertion here');
t.test('subtest', () => {});
}); 在处理异步代码时,可以使用 plan 函数来确保运行正确数量的断言:
【When working with asynchronous code, the plan function can be used to ensure that the
correct number of assertions are run:】
test('planning with streams', (t, done) => {
function* generate() {
yield 'a';
yield 'b';
yield 'c';
}
const expected = ['a', 'b', 'c'];
t.plan(expected.length);
const stream = Readable.from(generate());
stream.on('data', (chunk) => {
t.assert.strictEqual(chunk, expected.shift());
});
stream.on('end', () => {
done();
});
}); 使用 wait 选项时,你可以控制测试等待预期断言的时间。例如,设置最大等待时间可以确保测试在指定的时间范围内等待异步断言完成:
【When using the wait option, you can control how long the test will wait for the expected assertions.
For example, setting a maximum wait time ensures that the test will wait for asynchronous assertions
to complete within the specified timeframe:】
test('plan with wait: 2000 waits for async assertions', (t) => {
t.plan(1, { wait: 2000 }); // Waits for up to 2 seconds for the assertion to complete.
const asyncActivity = () => {
setTimeout(() => {
t.assert.ok(true, 'Async assertion completed within the wait time');
}, 1000); // Completes after 1 second, within the 2-second wait time.
};
asyncActivity(); // The test will pass because the assertion is completed in time.
}); 注意:如果指定了 wait 超时,只有在测试函数执行完毕后,才会开始倒计时。
【Note: If a wait timeout is specified, it begins counting down only after the test function finishes executing.】