Registry / testing / egg-mock

egg-mock

JSON →
library5.15.2jsnpmunverified

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-mock
INSTALL
IMPORT
SIG · EGG-MOCK
E
egg-mock
testingjavascriptv5.15.2
Install
—
Import
—
Disk
—
Pass rate
0/ 6
Env Coverage0 / 6
glibc
18–22
musl
18–22
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18–226 runs
build_error
glibc
node 18–226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

mm
✓ import mm from 'egg-mock';
✗ const mm = require('egg-mock');
While `require` is common in older Egg.js projects, v6+ supports ESM imports. Use default import for the `mm` object.
Application
✓ import { Application } from 'egg';
✗ import { Application } from 'egg-mock';
The `Application` type is typically imported from the `egg` package itself for type-checking when setting up mock applications.
mock
✓ import { mock } from 'egg-mock/bootstrap';
✗ import { mock } from 'egg-mock';
For `mock` functions that are automatically reset in `afterEach` (e.g., when using `egg-bin`), import from the `bootstrap` entry point.

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.

import mm from 'egg-mock'; import path from 'path'; import assert from 'assert'; import { Application } from 'egg'; // Assuming 'egg' types are available describe('Basic Egg.js Application Testing', () => { let app: Application; // Use egg's Application type for clarity // 1. Setup: Create a mock Egg.js application before all tests before(async () => { // mm.app starts an Egg application instance in test mode app = mm.app({ baseDir: path.join(__dirname, 'fixtures/apps/simple-app'), // Path to a minimal test application // customEgg: path.join(__dirname, '../node_modules/egg'), // Specify egg framework path if not default }); // Wait for the application to be fully initialized and ready await app.ready(); }); // 2. Teardown: Close the mock application gracefully after all tests after(() => app.close()); // 3. Cleanup: Restore all mocked data after each test to prevent side effects afterEach(mm.restore); it('should make a GET request to / and receive a 200 response', async () => { // Mock a service method to control its behavior during the test app.mockService('home', 'getGreeting', (name: string) => `Hello, ${name} from mock!`); // Use app.httpRequest() (based on supertest) to simulate an HTTP request const response = await app.httpRequest() .get('/') // The route to test .expect(200); // Expect an HTTP 200 OK status // Assert the response body content (assuming / calls home.getGreeting('world')) assert.strictEqual(response.text, 'Hello, world from mock!'); }); it('should allow mocking the application configuration', async () => { // Mock a specific configuration item app.mockConfig('middleware', ['myCustomMiddleware']); // Access the mocked config (actual effect might require app restart for some configs) assert.deepStrictEqual(app.config.middleware, ['myCustomMiddleware']); }); it('should mock a context property', async () => { // Create a new mock context instance const ctx = app.mockContext({ foo: 'bar', userId: 123, }); // Assert the mocked properties on the context assert.strictEqual(ctx.foo, 'bar'); assert.strictEqual(ctx.userId, 123); }); });
Debug
Known issues
breakingegg-mock v6.0.0 and later drops support for Node.js versions older than 18.19.0. Projects using older Node.js runtimes must upgrade Node.js or remain on egg-mock v5.x.
fix
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.
affects: >=6.0.0
gotchaFailing to call `mm.restore()` after each test can lead to global state pollution, causing tests to be interdependent and results to be inconsistent.
fix
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.
affects: >=1.0.0
gotchaWhen using `mm.cluster()` for multi-process application testing, you cannot directly access worker attributes or application APIs. All interactions must be made via `app.httpRequest()` (SuperTest).
fix
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.
affects: >=1.0.0
gotchaWith the introduction of v6.0.0, `egg-mock` supports both CommonJS (`require`) and ES Modules (`import`). Mixing module syntaxes incorrectly in your project or build configuration can lead to import errors.
fix
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.
affects: >=6.0.0
Errors
Common errors & fixes
Error: This version of Node.js (vX.Y.Z) is not supported. Please upgrade to Node.js v18.19.0 or higher.
Running `egg-mock` v6 or newer on a Node.js version older than 18.19.0.
fix
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`.
TypeError: Cannot read properties of undefined (reading 'mockService') (or similar for other app.mock* methods)
`mm.app()` was called, but `await app.ready()` was not completed before attempting to use application-specific mock methods like `app.mockService` or `app.mockContext`.
fix
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.
Test suite fails inconsistently, with data from one test affecting others.
Missing `mm.restore()` call after each test, which prevents cleanup of global mocks or mocked application state.
fix
Add `afterEach(mm.restore);` to your test suite to reset all mocks after every test runs, ensuring isolation.
ReferenceError: mm is not defined
Incorrect module import syntax (e.g., trying to use `require` in an ESM module or vice-versa, or incorrect named/default import).
fix
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.
Upgrade
Version history
5.15.2latest on npm
Audit
Dependencies
eggrequiredPeer dependency, as egg-mock is designed specifically for Egg.js applications.
mocharequiredPeer dependency, commonly used as the test runner for Egg.js projects.
urllibrequiredPeer dependency for HTTP client functionalities within Egg.js, used for mocking HTTP requests.
Agent activity
8 hits · last 30 days
node
8
Resources
egg-mock — npm install egg-mock · libregistry