Skip to content

test_runner: add cleanup function support to before() hooks#62166

Open
mattskel wants to merge 1 commit intonodejs:mainfrom
mattskel:test-55853-cleanup-function
Open

test_runner: add cleanup function support to before() hooks#62166
mattskel wants to merge 1 commit intonodejs:mainfrom
mattskel:test-55853-cleanup-function

Conversation

@mattskel
Copy link

@mattskel mattskel commented Mar 9, 2026

Summary

This PR implements cleanup function support for before() hooks in the Node.js test runner, allowing test setup code to register teardown logic that runs after all after() hooks complete.

Motivation

Currently, the test runner lacks a symmetric teardown mechanism for before() hooks. While after() hooks exist, they don't provide the same locality of setup/teardown that cleanup functions offer. This pattern is common in other testing frameworks (e.g., Vitest, Jest) and improves test maintainability by keeping related setup and teardown code together.

Fixes: #55853

Key Features

LIFO Execution: Multiple cleanup functions execute in reverse order (last registered, first executed)
Async Support: Cleanup functions can be async
Error Handling: Errors in cleanup functions don't prevent other cleanups from running
Late Registration: Supports before() hooks registered inside test bodies

Implementation Details

  1. Cleanup Storage:
  • Added cleanup: [] array to this.hooks object
  • Cleanup functions are captured in runHook() for normal before hooks
  • Cleanup functions are captured in createHook() for late-registered hooks
  1. Late-Registered Hook Tracking:
  • Added this.pendingBeforeHooks array to track promises from late-registered hooks
  • Uses async IIFE pattern to run late-registered hooks immediately and capture cleanup
  • Synchronization barrier ensures all pending hooks complete before after hooks run
  1. Cleanup Execution (runCleanup() method):
  • Iterates cleanup array in reverse (LIFO)
  • Awaits each cleanup function
  • Continues execution even if individual cleanups fail

Add tests for cleanup hooks.
Cleanup hook is returned from before hook.
Await before hooks before executing cleanup hooks.

Fixes: nodejs#55853
Refs: nodejs#55853 (comment)
@nodejs-github-bot
Copy link
Collaborator

Review requested:

  • @nodejs/test_runner

@nodejs-github-bot nodejs-github-bot added needs-ci PRs that need a full CI run. test_runner Issues and PRs related to the test runner subsystem. labels Mar 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-ci PRs that need a full CI run. test_runner Issues and PRs related to the test runner subsystem.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

test_runner: t.after should respect the first-in-last-out principle like Golang's defer

2 participants