egg-mock is a dedicated testing utility for Egg.js applications, plugins, and custom Egg frameworks. It provides robust mocking capabilities, extending the functionalities of `node_modules/mm`. The library allows developers to simulate various aspects of an Egg.js application's environment, including application instances (`mm.app`), multi-process clusters (`mm.cluster`), environment variables (`mm.env`), and user home directories (`mm.home`). It also offers fine-grained control over console logging levels. Currently in stable version `6.0.7`, egg-mock maintains an active release cadence, with frequent updates addressing bugs and improving compatibility. Major version `6.0.0` was released in December 2024. Key differentiators include its tight integration with the Egg.js ecosystem, enabling comprehensive end-to-end testing scenarios, and its ability to handle both single and multi-process application mocking. It ships with TypeScript type definitions for an enhanced developer experience.
npm install egg-mockVerified import paths — ran on the pinned version, not inferred.
Demonstrates basic setup and teardown for testing an Egg.js application using `egg-mock`, including creating a mock app, making HTTP requests, mocking services, and managing test state with `mm.restore`. The code assumes a simple 'simple-app' fixture is present for context.
Upgrade your Node.js environment to 18.19.0 or higher. Alternatively, pin your `egg-mock` dependency to a `5.x` version (e.g., `"egg-mock": "^5.0.0"`) to maintain compatibility with older Node.js versions.
Always include `afterEach(mm.restore);` in your test files to ensure all mocked data is cleaned up between tests. If using `egg-bin`, this might be auto-injected.
Ensure that tests for clustered applications only use `app.httpRequest()` to make requests and verify responses. Avoid attempting to access `app.context` or other direct application properties.
Ensure consistent module usage. For ESM, use `import mm from 'egg-mock';`. For CommonJS, use `const mm = require('egg-mock');`. Verify your `tsconfig.json` (if using TypeScript) and `package.json` (`"type": "module"` or file extensions like `.mjs`/`.cjs`) are configured correctly for your chosen module system.Update your Node.js runtime to version 18.19.0 or higher. Alternatively, downgrade `egg-mock` to a `5.x` version in your `package.json`.
Always `await app.ready()` after initializing the mock application with `mm.app()` to ensure the application instance is fully initialized and its methods are available.
Add `afterEach(mm.restore);` to your test suite to reset all mocks after every test runs, ensuring isolation.
Ensure you are using the correct import statement for your module environment: `import mm from 'egg-mock';` for ESM, or `const mm = require('egg-mock');` for CommonJS. For TypeScript, ensure your `tsconfig.json` `module` and `moduleResolution` settings align with your chosen output.