子测试


¥Subtests

测试上下文的 test() 方法允许创建子测试。它允许你以分层方式构建测试,你可以在更大的测试中创建嵌套测试。此方法的行为与顶层 test() 函数相同。以下示例演示了如何创建具有两个子测试的顶层测试。

¥The test context's test() method allows subtests to be created. It allows you to structure your tests in a hierarchical manner, where you can create nested tests within a larger test. This method behaves identically to the top level test() function. The following example demonstrates the creation of a top level test with two subtests.

test('top level test', async (t) => {
  await t.test('subtest 1', (t) => {
    assert.strictEqual(1, 1);
  });

  await t.test('subtest 2', (t) => {
    assert.strictEqual(2, 2);
  });
}); 

注意:beforeEachafterEach 钩子在每个子测试执行之间触发。

¥Note: beforeEach and afterEach hooks are triggered between each subtest execution.

在本示例中,await 用于确保两个子测试均已完成。这是必要的,因为测试不会等待其子测试完成,这与套件中创建的测试不同。当父测试完成时仍然未完成的任何子测试将被取消并视为失败。任何子测试失败都会导致父测试失败。

¥In this example, await is used to ensure that both subtests have completed. This is necessary because tests do not wait for their subtests to complete, unlike tests created within suites. Any subtests that are still outstanding when their parent finishes are cancelled and treated as failures. Any subtest failures cause the parent test to fail.