context.plan(count[,options])


  • count <number> 预期要运行的断言和子测试的数量。
  • options <Object> 计划的附加选项。
    • wait <boolean> | <number> 计划的等待时间:
      • 如果为 true,计划将无限期等待所有断言和子测试运行完成。
      • 如果为 false,计划将在测试函数完成后立即进行检查,而不等待任何未完成的断言或子测试。任何在此检查之后完成的断言或子测试将不会计入计划中。
      • 如果是数字,它指定在等待预期断言和子测试匹配时的最大等待时间(以毫秒为单位)。如果达到超时,测试将失败。默认值: 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

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.】