{"id":13366,"library":"jest-after-this","title":"Jest afterThis Hook","description":"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.","status":"active","version":"1.0.4","language":"javascript","source_language":"en","source_url":"https://github.com/illBeRoy/jest-after-this","tags":["javascript","jest","tests","testing","tdd","typescript"],"install":[{"cmd":"npm install jest-after-this","lang":"bash","label":"npm"},{"cmd":"yarn add jest-after-this","lang":"bash","label":"yarn"},{"cmd":"pnpm add jest-after-this","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Peer dependency as it's a Jest extension","package":"jest","optional":false}],"imports":[{"note":"Primarily designed for ESM usage in modern Jest setups, though CommonJS `require` might work with transpilation, direct ESM import is preferred.","wrong":"const { afterThis } = require('jest-after-this');","symbol":"afterThis","correct":"import { afterThis } from 'jest-after-this';"}],"quickstart":{"code":"import { afterThis } from 'jest-after-this';\nimport fs from 'fs';\nimport path from 'path';\n\n// A helper function that creates a temporary file and schedules its cleanup\nfunction createTempFileForTest(filename: string) {\n  const filePath = path.join(__dirname, 'temp', filename);\n  if (!fs.existsSync(path.dirname(filePath))) {\n    fs.mkdirSync(path.dirname(filePath), { recursive: true });\n  }\n  fs.writeFileSync(filePath, `Content for ${filename}`);\n  afterThis(() => {\n    try {\n      fs.rmSync(filePath);\n      console.log(`Cleaned up: ${filePath}`);\n    } catch (error) {\n      console.error(`Failed to clean up ${filePath}:`, error.message);\n    }\n  });\n  return filePath;\n}\n\ndescribe('File operations', () => {\n  it('should create one temporary file and clean it up', () => {\n    const file1 = createTempFileForTest('test-file-1.txt');\n    expect(fs.existsSync(file1)).toBe(true);\n    // After this test, file1 will be deleted by the afterThis hook\n  });\n\n  it('should create multiple temporary files and clean them up', () => {\n    const file2 = createTempFileForTest('test-file-2.txt');\n    const file3 = createTempFileForTest('test-file-3.txt');\n    expect(fs.existsSync(file2)).toBe(true);\n    expect(fs.existsSync(file3)).toBe(true);\n    // After this test, file3 then file2 will be deleted by their respective afterThis hooks\n  });\n\n  afterAll(() => {\n    // Ensure the temp directory itself is clean after all tests\n    const tempDir = path.join(__dirname, 'temp');\n    if (fs.existsSync(tempDir)) {\n      fs.rmSync(tempDir, { recursive: true, force: true });\n      console.log(`Cleaned up temp directory: ${tempDir}`);\n    }\n  });\n});","lang":"typescript","description":"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."},"warnings":[{"fix":"Be mindful of handler order if dependencies exist between cleanup actions. If specific order is crucial, register dependent cleanups first.","message":"Handlers registered with `afterThis` execute in reverse order of their registration within a test. The last `afterThis` call's handler will run first.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Consider what types of cleanup belong in `afterEach` (global, per-test setup teardown) versus `afterThis` (dynamic, test-specific side effect cleanup).","message":"`afterThis` has a lower priority than `afterEach` hooks. This means all `afterEach` handlers will complete before the first `afterThis` handler begins execution.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure all calls to `afterThis` are made inside the callback function provided to `it()` or `test()`.","cause":"The `afterThis` function was invoked outside the scope of an `it` or `test` block, for example, directly in a `describe` block or a global context.","error":"Error: `afterThis` can only be called from within a test function (defined using `it` or `test`)."}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":"","cli_version":null}