Jest Environment Emitter

1.2.0 · active · verified Tue Apr 21

jest-environment-emit is a utility package for Jest that overcomes the limitation of having only one test environment per project. It provides a mechanism to add multiple event handlers to any Jest test environment, acting similarly to multiple test reporters. The package offers `WithEmitter`, a higher-order function to wrap custom environments, and pre-wrapped `TestEnvironment` classes for `jest-environment-node` and `jest-environment-jsdom` via subpath exports. Currently at version 1.2.0, released in June 2025, the package maintains a steady release cadence, frequently addressing compatibility with new Jest versions (e.g., Jest 30 support in v1.2.0) and refining import/export mechanisms for robust ESM and CJS interoperability. Its primary differentiator is enabling modular, composable event-driven logic within the Jest testing lifecycle, which is otherwise restricted to a single environment definition. It ships with full TypeScript types, enhancing developer experience.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates configuring Jest to use `jest-environment-emit/node` and attaching multiple event listener modules. It includes an example listener module showing how to subscribe to various Jest lifecycle events to perform custom setup, teardown, or other actions.

/** @type {import('jest').Config} */
module.exports = {
  testEnvironment: 'jest-environment-emit/node',
  testEnvironmentOptions: {
    eventListeners: [
      './jest-setup-listener.js',
      ['./jest-parametrized-listener.js', { some: 'options', token: process.env.API_TOKEN ?? '' }],
    ]
  },
};

// jest-setup-listener.js
/** @type {import('jest-environment-emit').EnvironmentListenerFn} */
const setupListener = function (context, options) {
  context.testEvents
    .on('test_environment_setup', async ({ env }) => {
      console.log('Test environment setup initiated!');
      env.global.__MY_CUSTOM_GLOBAL__ = 'initialized from listener';
    })
    .on('test_start', ({ event, state }) => {
      console.log(`Starting test: ${event.test.name}`);
    })
    .on('test_environment_teardown', async ({ env }) => {
      console.log('Test environment teardown completed!');
      delete env.global.__MY_CUSTOM_GLOBAL__;
    });
};

export default setupListener;

view raw JSON →