jest-after-this is a Jest extension providing a new lifecycle hook, `afterThis`, which schedules code to run dynamically after the current test completes. Unlike `afterEach`, `afterThis` can be called multiple times within a single test to manage specific, unique side effects, ensuring cleanup even if the test fails. It is currently at version 1.0.4, with a recent release (v1.0.2) focused on release tooling, suggesting a maintenance or active, but not rapid, release cadence. Its key differentiator is the ability to tie cleanup directly to the test that created the side effect, promoting self-cleaning test helpers and reducing the complexity of shared `afterEach` hooks for diverse test scenarios. Handlers are executed in reverse order of registration and support asynchronous operations.
npm install jest-after-thisVerified import paths — ran on the pinned version, not inferred.
Demonstrates creating a self-cleaning helper function that uses `afterThis` to manage temporary files for specific tests, ensuring proper cleanup after each test, even with multiple file creations.
Be mindful of handler order if dependencies exist between cleanup actions. If specific order is crucial, register dependent cleanups first.
Consider what types of cleanup belong in `afterEach` (global, per-test setup teardown) versus `afterThis` (dynamic, test-specific side effect cleanup).
Ensure all calls to `afterThis` are made inside the callback function provided to `it()` or `test()`.