context.plan(count[,options])
-
count
<number> 预期运行的断言和子测试的数量。¥
count
<number> The number of assertions and subtests that are expected to run. -
options
<Object> 计划的其他选项。¥
options
<Object> Additional options for the plan.-
wait
<boolean> | <number> 计划的等待时间:¥
wait
<boolean> | <number> The wait time for the plan:-
如果是
true
,计划会无限期地等待所有断言和子测试运行。¥If
true
, the plan waits indefinitely for all assertions and subtests to run. -
如果是
false
,计划会在测试函数完成后立即执行检查,而无需等待任何待处理的断言或子测试。在此检查后完成的任何断言或子测试都不会计入计划。¥If
false
, the plan performs an immediate check after the test function completes, without waiting for any pending assertions or subtests. Any assertions or subtests that complete after this check will not be counted towards the plan. -
如果是数字,则它指定在等待预期的断言和子测试匹配时超时前的最大等待时间(以毫秒为单位)。如果达到超时,测试将失败。默认值:
false
。¥If a number, it specifies the maximum wait time in milliseconds before timing out while waiting for expected assertions and subtests to be matched. If the timeout is reached, the test will fail. Default:
false
.
-
-
此函数用于设置预期在测试中运行的断言和子测试的数量。如果运行的断言和子测试的数量与预期计数不匹配,则测试将失败。
¥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
。¥Note: To make sure assertions are tracked,
t.assert
must be used instead ofassert
directly.
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.