CodeSampleX

示例

@vitest/runner 2.1.9: afterEach

已验证示例 — npm @vitest/runner 2.1.9: afterEach. contract 在 node 22 · linux debian/x64 · docker 上运行并通过: afterEach registers a teardown hook that executes once…

sha256:ec000d58d81d5dc3ca80e24ca46592da7eda17061e290ccfd023d45f01990c7b

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

验证运行环境

环境 契约 阶段 运行日期
node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2…
2026-09-06

案例

HOW
目标
verify @vitest/runner.afterEach in pkg:npm/%40vitest/runner@2.1.9
包
符号
  • @vitest/runner.afterEach
环境
node 22.23.2
创建时间
2026-09-06T22:29:49Z

契约

  1. afterEach registers a teardown hook that executes once after each test in a suite completes
  2. afterEach executes even when a test in the suite fails
  3. multiple afterEach hooks execute in reverse registration order under stack sequence and forward order under list sequence
  4. afterEach supports asynchronous cleanup functions and startTests awaits their completion
  5. nested suite afterEach hooks execute child hooks before enclosing parent suite hooks for each test
  6. errors thrown in afterEach mark the test task as failed and attach the error
  7. afterEach accepts a custom timeout and fails the test when execution exceeds that limit
  8. afterEach receives a TestContext object providing task metadata and lifecycle utilities

文件

  • PROMPT.md
  • csx.json
  • index.mjs
  • package-lock.json
  • package.json
  • spec.json
  • test/contract.mjs

下载源代码构件 (tar.gz)

源代码

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify @vitest/runner.afterEach in pkg:npm/%40vitest/runner@2.1.9
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40vitest/runner@2.1.9
Demonstrate these symbols/APIs:
  - @vitest/runner.afterEach

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:6c9332bb7005ccabf40841c63e97521240c701d23dbd0dde71f0ba948a5c5c75","contract":["afterEach registers a teardown hook that executes once after each test in a suite completes","afterEach executes even when a test in the suite fails","multiple afterEach hooks execute in reverse registration order under stack sequence and forward order under list sequence","afterEach supports asynchronous cleanup functions and startTests awaits their completion","nested suite afterEach hooks execute child hooks before enclosing parent suite hooks for each test","errors thrown in afterEach mark the test task as failed and attach the error","afterEach accepts a custom timeout and fails the test when execution exceeds that limit","afterEach receives a TestContext object providing task metadata and lifecycle utilities"],"goal":"verify @vitest/runner.afterEach in pkg:npm/%40vitest/runner@2.1.9","kind":"HOW","packages":["pkg:npm/%40vitest/runner@2.1.9"],"schemaVersion":1,"symbols":["@vitest/runner.afterEach"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/%40vitest/runner@2.1.9"],"schemaVersion":1,"subject":"pkg:npm/%40vitest/runner@2.1.9","symbols":["@vitest/runner.afterEach"],"verifierAdapter":"node-typescript@1"}
index.mjs
import {
  startTests,
  describe,
  it,
  test,
  suite,
  beforeAll,
  afterAll,
  beforeEach,
  afterEach,
} from "@vitest/runner";

/**
 * Creates a minimal VitestRunner instance configured for in-memory test execution.
 *
 * @param {Function} importHandler - Async function called to define or import tests
 * @param {Object} [configOverrides] - Optional configuration overrides
 * @returns {Object} A VitestRunner-compatible runner object
 */
export function createRunner(importHandler, configOverrides = {}) {
  return {
    config: {
      root: process.cwd(),
      setupFiles: [],
      name: "vitest-runner-aftereach",
      passWithNoTests: true,
      testNamePattern: undefined,
      allowOnly: true,
      sequence: {
        seed: 42,
        hooks: "stack",
        setupFiles: "list",
        shuffle: false,
      },
      chaiConfig: undefined,
      maxConcurrency: 5,
      testTimeout: 5000,
      hookTimeout: 5000,
      retry: 0,
      includeTaskLocation: false,
      ...configOverrides,
    },
    importFile: async (filepath) => {
      if (typeof importHandler === "function") {
        await importHandler(filepath);
      }
    },
  };
}

/**
 * Executes an in-memory suite definition using @vitest/runner startTests.
 *
 * @param {Function} suiteDefinition - Function defining describe/test/afterEach blocks
 * @param {string} [specName='spec.test.js'] - Virtual test spec name
 * @param {Object} [configOverrides] - Optional runner configuration overrides
 * @returns {Promise<Array>} Array of executed test file results
 */
export async function runSuite(suiteDefinition, specName = "spec.test.js", configOverrides = {}) {
  const runner = createRunner(async () => {
    suiteDefinition();
  }, configOverrides);

  return await startTests([specName], runner);
}

export {
  startTests,
  describe,
  it,
  test,
  suite,
  beforeAll,
  afterAll,
  beforeEach,
  afterEach,
};
package-lock.json
{
  "name": "sample-vitest-runner-aftereach",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-vitest-runner-aftereach",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "@vitest/runner": "2.1.9"
      }
    },
    "node_modules/@vitest/pretty-format": {
      "version": "2.1.9",
      "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-2.1.9.tgz",
      "integrity": "sha512-KhRIdGV2U9HOUzxfiHmY8IFHTdqtOhIzCpd8WRdJiE7D/HUcZVD0EgQCVjm+Q9gkUXWgBvMmTtZgIG48wq7sOQ==",
      "license": "MIT",
      "dependencies": {
        "tinyrainbow": "^1.2.0"
      },
      "funding": {
        "url": "https://opencollective.com/vitest"
      }
    },
    "node_modules/@vitest/runner": {
      "version": "2.1.9",
      "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-2.1.9.tgz",
      "integrity": "sha512-ZXSSqTFIrzduD63btIfEyOmNcBmQvgOVsPNPe0jYtESiXkhd8u2erDLnMxmGrDCwHCCHE7hxwRDCT3pt0esT4g==",
      "license": "MIT",
      "dependencies": {
        "@vitest/utils": "2.1.9",
        "pathe": "^1.1.2"
      },
      "funding": {
        "url": "https://opencollective.com/vitest"
      }
    },
    "node_modules/@vitest/utils": {
      "version": "2.1.9",
      "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-2.1.9.tgz",
      "integrity": "sha512-v0psaMSkNJ3A2NMrUEHFRzJtDPFn+/VWZ5WxImB21T9fjucJRmS7xCS3ppEnARb9y11OAzaD+P2Ps+b+BGX5iQ==",
      "license": "MIT",
      "dependencies": {
        "@vitest/pretty-format": "2.1.9",
        "loupe": "^3.1.2",
        "tinyrainbow": "^1.2.0"
      },
      "funding": {
        "url": "https://opencollective.com/vitest"
      }
    },
    "node_modules/loupe": {
      "version": "3.2.1",
      "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz",
      "integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==",
      "license": "MIT"
    },
    "node_modules/pathe": {
      "version": "1.1.2",
      "resolved": "https://registry.npmjs.org/pathe/-/pathe-1.1.2.tgz",
      "integrity": "sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==",
      "license": "MIT"
    },
    "node_modules/tinyrainbow": {
      "version": "1.2.0",
      "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-1.2.0.tgz",
      "integrity": "sha512-weEDEq7Z5eTHPDh4xjX789+fHfF+P8boiFB+0vbWzpbnbsEr/GRaohi/uMKxg8RZMXnl1ItAi/IUHWMsjDV7kQ==",
      "license": "MIT",
      "engines": {
        "node": ">=14.0.0"
      }
    }
  }
}
package.json
{
  "name": "sample-vitest-runner-aftereach",
  "version": "1.0.0",
  "description": "Clean-room verification of @vitest/runner.afterEach in @vitest/runner@2.1.9",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "@vitest/runner": "2.1.9"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify @vitest/runner.afterEach in pkg:npm/%40vitest/runner@2.1.9",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40vitest/runner@2.1.9"
  ],
  "symbols": [
    "@vitest/runner.afterEach"
  ]
}
test/contract.mjs
import assert from "node:assert/strict";
import {
  createRunner,
  runSuite,
  startTests,
  describe,
  it,
  test,
  afterEach,
} from "../index.mjs";

// 1. Exported symbol verification
{
  assert.equal(typeof afterEach, "function", "afterEach must be an exported function");
  assert.equal(typeof runSuite, "function", "runSuite helper must be an exported function");
  assert.equal(typeof createRunner, "function", "createRunner must be an exported function");
}

// 2. afterEach registers a teardown hook that executes once after each test in a suite completes
{
  const events = [];
  const files = await runSuite(() => {
    describe("Suite 1", () => {
      afterEach((context) => {
        events.push(`afterEach:${context.task.name}`);
      });
      test("test 1", () => {
        events.push("test-1");
      });
      test("test 2", () => {
        events.push("test-2");
      });
    });
  }, "suite1.test.js");

  assert.equal(files.length, 1);
  assert.equal(files[0].result?.state, "pass");
  assert.deepEqual(events, ["test-1", "afterEach:test 1", "test-2", "afterEach:test 2"]);
}

// 3. afterEach executes even when a test in the suite fails
{
  const events = [];
  const files = await runSuite(() => {
    describe("Suite with failing test", () => {
      afterEach((context) => {
        events.push(`afterEach:${context.task.name}`);
      });
      test("failing test", () => {
        events.push("test-failed");
        assert.fail("intentional failure");
      });
      test("passing test", () => {
        events.push("test-passed");
      });
    });
  }, "suite-fail.test.js");

  const tasks = files[0].tasks[0].tasks;
  assert.equal(tasks[0].result?.state, "fail");
  assert.equal(tasks[1].result?.state, "pass");
  assert.deepEqual(events, [
    "test-failed",
    "afterEach:failing test",
    "test-passed",
    "afterEach:passing test",
  ]);
}

// 4. multiple afterEach hooks execute in reverse registration order under stack sequence and forward order under list sequence
{
  const stackEvents = [];
  await runSuite(() => {
    describe("Stack hook ordering", () => {
      afterEach(() => { stackEvents.push("first-hook"); });
      afterEach(() => { stackEvents.push("second-hook"); });
      test("run test", () => { stackEvents.push("test"); });
    });
  }, "stack.test.js", { sequence: { hooks: "stack", shuffle: false } });
  assert.deepEqual(stackEvents, ["test", "second-hook", "first-hook"]);

  const listEvents = [];
  await runSuite(() => {
    describe("List hook ordering", () => {
      afterEach(() => { listEvents.push("first-hook"); });
      afterEach(() => { listEvents.push("second-hook"); });
      test("run test", () => { listEvents.push("test"); });
    });
  }, "list.test.js", { sequence: { hooks: "list", shuffle: false } });
  assert.deepEqual(listEvents, ["test", "first-hook", "second-hook"]);
}

// 5. afterEach supports asynchronous cleanup functions and startTests awaits their completion
{
  let asyncFinished = false;
  const files = await runSuite(() => {
    describe("Async cleanup", () => {
      afterEach(async () => {
        await new Promise((resolve) => setTimeout(resolve, 30));
        asyncFinished = true;
      });
      test("work test", () => {
        assert.equal(asyncFinished, false);
      });
    });
  }, "async.test.js");

  assert.equal(files[0].result?.state, "pass");
  assert.equal(asyncFinished, true);
}

// 6. nested suite afterEach hooks execute child hooks before enclosing parent suite hooks for each test
{
  const events = [];
  const files = await runSuite(() => {
    describe("Parent Suite", () => {
      afterEach(() => { events.push("parent-afterEach"); });
      describe("Child Suite", () => {
        afterEach(() => { events.push("child-afterEach"); });
        test("child test", () => { events.push("child-test"); });
      });
      test("parent test", () => { events.push("parent-test"); });
    });
  }, "nested.test.js");

  assert.equal(files[0].result?.state, "pass");
  assert.deepEqual(events, [
    "child-test",
    "child-afterEach",
    "parent-afterEach",
    "parent-test",
    "parent-afterEach",
  ]);
}

// 7. errors thrown in afterEach mark the test task as failed and attach the error
{
  const files = await runSuite(() => {
    describe("Suite with throwing afterEach", () => {
      afterEach(() => {
        throw new Error("teardown error in afterEach hook");
      });
      test("successful test", () => {
        assert.ok(true);
      });
    });
  }, "throwing-aftereach.test.js");

  const task = files[0].tasks[0].tasks[0];
  assert.equal(task.result?.state, "fail");
  assert.ok(task.result?.errors && task.result.errors.length > 0);
  assert.match(task.result.errors[0].message, /teardown error in afterEach hook/);
}

// 8. afterEach accepts a custom timeout and fails the test when execution exceeds that limit
{
  const files = await runSuite(() => {
    describe("Suite with timed out afterEach", () => {
      afterEach(async () => {
        await new Promise((resolve) => setTimeout(resolve, 60));
      }, 10);
      test("fast test", () => {
        assert.ok(true);
      });
    });
  }, "timeout-aftereach.test.js");

  const task = files[0].tasks[0].tasks[0];
  assert.equal(task.result?.state, "fail");
  assert.ok(task.result?.errors && task.result.errors.length > 0);
  assert.match(task.result.errors[0].message, /Hook timed out in 10ms/);
}

// 9. afterEach receives a TestContext object providing task metadata and lifecycle utilities
{
  let capturedTaskName = null;
  let hasLifecycleUtilities = false;
  const files = await runSuite(() => {
    describe("Context Suite", () => {
      afterEach((context) => {
        capturedTaskName = context.task?.name;
        hasLifecycleUtilities =
          typeof context.onTestFailed === "function" &&
          typeof context.onTestFinished === "function" &&
          typeof context.skip === "function";
      });
      test("context validation test", () => {
        assert.ok(true);
      });
    });
  }, "context.test.js");

  assert.equal(files[0].result?.state, "pass");
  assert.equal(capturedTaskName, "context validation test");
  assert.equal(hasLifecycleUtilities, true);
}

console.log("All @vitest/runner.afterEach contract assertions passed successfully.");

原始种子者

匿名