CodeSampleX

Ejemplo

@vitest/runner 2.1.9: afterEach

Muestra verificada para npm @vitest/runner 2.1.9: afterEach. El contrato se ejecutó en node 22 · linux debian/x64 · docker y pasó.

sha256:ec000d58d81d5dc3ca80e24ca46592da7eda17061e290ccfd023d45f01990c7b

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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

Caso

HOW
Objetivo
verify @vitest/runner.afterEach in pkg:npm/%40vitest/runner@2.1.9
Paquetes
Símbolos
  • @vitest/runner.afterEach
Entorno
node 22.23.2
Creado
2026-09-06T22:29:49Z

Contrato

  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

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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.");

Seeder de origen

anónimo