CodeSampleX

Пример

@vitest/runner 2.1.9: afterAll

Проверенный пример — npm @vitest/runner 2.1.9: afterAll. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден: afterAll registers a teardown…

sha256:06e500897416b1db210d9a29c4d0431b37c38d69600d3b93463259e86848f1c5

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда linux 24 · ubuntu · glibc 2.39 x64 npm

Среды запусков проверки

Окружение Контракт Этапы Запуск
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.afterAll in pkg:npm/%40vitest/runner@2.1.9
Пакеты
Символы
  • @vitest/runner.afterAll
Создан
2026-09-06T21:06:10Z

Контракт

  1. afterAll registers a teardown hook that executes once after all tests in a suite complete
  2. afterAll executes even when tests in the suite fail
  3. multiple afterAll hooks execute in reverse registration order under stack sequence and forward order under list sequence
  4. afterAll supports asynchronous cleanup functions and startTests awaits their completion
  5. nested suite afterAll hooks execute before enclosing parent suite afterAll hooks
  6. errors thrown in afterAll mark the suite as failed while individual test states are preserved
  7. afterAll accepts a custom timeout and fails the suite when execution exceeds that limit
  8. afterAll receives the current suite as its parameter

Файлы

  • 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.afterAll 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.afterAll

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:48f1538e50336170e996ffdd8a6464f818c17e0a447fd8e179e1bcb39ded9941","contract":["afterAll registers a teardown hook that executes once after all tests in a suite complete","afterAll executes even when tests in the suite fail","multiple afterAll hooks execute in reverse registration order under stack sequence and forward order under list sequence","afterAll supports asynchronous cleanup functions and startTests awaits their completion","nested suite afterAll hooks execute before enclosing parent suite afterAll hooks","errors thrown in afterAll mark the suite as failed while individual test states are preserved","afterAll accepts a custom timeout and fails the suite when execution exceeds that limit","afterAll receives the current suite as its parameter"],"goal":"verify @vitest/runner.afterAll in pkg:npm/%40vitest/runner@2.1.9","kind":"HOW","packages":["pkg:npm/%40vitest/runner@2.1.9"],"schemaVersion":1,"symbols":["@vitest/runner.afterAll"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","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.afterAll"],"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-afterall",
      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,
      tags: [],
      tagsFilter: undefined,
      strictTags: 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/afterAll 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-afterall",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-vitest-runner-afterall",
      "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-afterall",
  "version": "1.0.0",
  "description": "Clean-room verification of @vitest/runner.afterAll 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.afterAll in pkg:npm/%40vitest/runner@2.1.9",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40vitest/runner@2.1.9"
  ],
  "symbols": [
    "@vitest/runner.afterAll"
  ]
}
test/contract.mjs
import assert from "node:assert/strict";
import {
  createRunner,
  runSuite,
  startTests,
  describe,
  it,
  test,
  afterAll,
} from "../index.mjs";

// 1. Exported symbol verification
{
  assert.equal(typeof afterAll, "function", "afterAll 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. afterAll registers a teardown hook that executes once after all tests in a suite complete
{
  const events = [];
  const files = await runSuite(() => {
    describe("Suite 1", () => {
      afterAll(() => {
        events.push("afterAll-run");
      });
      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", "test-2", "afterAll-run"]);
}

// 3. afterAll executes even when tests in the suite fail
{
  const events = [];
  const files = await runSuite(() => {
    describe("Suite with failed test", () => {
      afterAll(() => {
        events.push("afterAll-executed");
      });
      test("failing test", () => {
        events.push("test-failed");
        assert.fail("intentional failure");
      });
      test("passing test", () => {
        events.push("test-passed");
      });
    });
  }, "suite-fail.test.js");

  const suiteTask = files[0].tasks[0];
  assert.equal(suiteTask.result?.state, "fail");
  assert.deepEqual(events, ["test-failed", "test-passed", "afterAll-executed"]);
}

// 4. multiple afterAll hooks execute in reverse registration order under stack sequence and forward order under list sequence
{
  const stackEvents = [];
  await runSuite(() => {
    describe("Stack hook ordering", () => {
      afterAll(() => { stackEvents.push("first-hook"); });
      afterAll(() => { 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", () => {
      afterAll(() => { listEvents.push("first-hook"); });
      afterAll(() => { 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. afterAll supports asynchronous cleanup functions and startTests awaits their completion
{
  let asyncFinished = false;
  const files = await runSuite(() => {
    describe("Async cleanup", () => {
      afterAll(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 afterAll hooks execute before enclosing parent suite afterAll hooks
{
  const events = [];
  const files = await runSuite(() => {
    describe("Parent Suite", () => {
      afterAll(() => { events.push("parent-afterAll"); });
      describe("Child Suite", () => {
        afterAll(() => { events.push("child-afterAll"); });
        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-afterAll",
    "parent-test",
    "parent-afterAll",
  ]);
}

// 7. errors thrown in afterAll mark the suite as failed while individual test states are preserved
{
  const files = await runSuite(() => {
    describe("Suite with throwing afterAll", () => {
      afterAll(() => {
        throw new Error("teardown error in afterAll hook");
      });
      test("successful test", () => {
        assert.ok(true);
      });
    });
  }, "throwing-afterall.test.js");

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

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

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

// 9. afterAll receives the current suite as its parameter
{
  let capturedSuiteName = null;
  const files = await runSuite(() => {
    describe("Suite with suite parameter", () => {
      afterAll((suite) => {
        capturedSuiteName = suite.name;
      });
      test("suite parameter test", () => {
        assert.ok(true);
      });
    });
  }, "suite-param.test.js");

  assert.equal(files[0].result?.state, "pass");
  assert.equal(capturedSuiteName, "Suite with suite parameter");
}

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

Исходный сидер

аноним