{"id":13106,"library":"egg-mock","title":"Egg.js Mock Testing Utility","description":"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.","status":"active","version":"5.15.2","language":"javascript","source_language":"en","source_url":"https://github.com/eggjs/egg-mock","tags":["javascript","egg","mock","typescript"],"install":[{"cmd":"npm install egg-mock","lang":"bash","label":"npm"},{"cmd":"yarn add egg-mock","lang":"bash","label":"yarn"},{"cmd":"pnpm add egg-mock","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Peer dependency, as egg-mock is designed specifically for Egg.js applications.","package":"egg","optional":false},{"reason":"Peer dependency, commonly used as the test runner for Egg.js projects.","package":"mocha","optional":false},{"reason":"Peer dependency for HTTP client functionalities within Egg.js, used for mocking HTTP requests.","package":"urllib","optional":false}],"imports":[{"note":"While `require` is common in older Egg.js projects, v6+ supports ESM imports. Use default import for the `mm` object.","wrong":"const mm = require('egg-mock');","symbol":"mm","correct":"import mm from 'egg-mock';"},{"note":"The `Application` type is typically imported from the `egg` package itself for type-checking when setting up mock applications.","wrong":"import { Application } from 'egg-mock';","symbol":"Application","correct":"import { Application } from 'egg';"},{"note":"For `mock` functions that are automatically reset in `afterEach` (e.g., when using `egg-bin`), import from the `bootstrap` entry point.","wrong":"import { mock } from 'egg-mock';","symbol":"mock","correct":"import { mock } from 'egg-mock/bootstrap';"}],"quickstart":{"code":"import mm from 'egg-mock';\nimport path from 'path';\nimport assert from 'assert';\nimport { Application } from 'egg'; // Assuming 'egg' types are available\n\ndescribe('Basic Egg.js Application Testing', () => {\n  let app: Application; // Use egg's Application type for clarity\n\n  // 1. Setup: Create a mock Egg.js application before all tests\n  before(async () => {\n    // mm.app starts an Egg application instance in test mode\n    app = mm.app({\n      baseDir: path.join(__dirname, 'fixtures/apps/simple-app'), // Path to a minimal test application\n      // customEgg: path.join(__dirname, '../node_modules/egg'), // Specify egg framework path if not default\n    });\n    // Wait for the application to be fully initialized and ready\n    await app.ready();\n  });\n\n  // 2. Teardown: Close the mock application gracefully after all tests\n  after(() => app.close());\n\n  // 3. Cleanup: Restore all mocked data after each test to prevent side effects\n  afterEach(mm.restore);\n\n  it('should make a GET request to / and receive a 200 response', async () => {\n    // Mock a service method to control its behavior during the test\n    app.mockService('home', 'getGreeting', (name: string) => `Hello, ${name} from mock!`);\n\n    // Use app.httpRequest() (based on supertest) to simulate an HTTP request\n    const response = await app.httpRequest()\n      .get('/') // The route to test\n      .expect(200); // Expect an HTTP 200 OK status\n\n    // Assert the response body content (assuming / calls home.getGreeting('world'))\n    assert.strictEqual(response.text, 'Hello, world from mock!');\n  });\n\n  it('should allow mocking the application configuration', async () => {\n    // Mock a specific configuration item\n    app.mockConfig('middleware', ['myCustomMiddleware']);\n\n    // Access the mocked config (actual effect might require app restart for some configs)\n    assert.deepStrictEqual(app.config.middleware, ['myCustomMiddleware']);\n  });\n\n  it('should mock a context property', async () => {\n    // Create a new mock context instance\n    const ctx = app.mockContext({\n      foo: 'bar',\n      userId: 123,\n    });\n    // Assert the mocked properties on the context\n    assert.strictEqual(ctx.foo, 'bar');\n    assert.strictEqual(ctx.userId, 123);\n  });\n});","lang":"typescript","description":"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."},"warnings":[{"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.","message":"egg-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.","severity":"breaking","affected_versions":">=6.0.0"},{"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.","message":"Failing to call `mm.restore()` after each test can lead to global state pollution, causing tests to be interdependent and results to be inconsistent.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"When 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).","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"With 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.","severity":"gotcha","affected_versions":">=6.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"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`.","cause":"Running `egg-mock` v6 or newer on a Node.js version older than 18.19.0.","error":"Error: This version of Node.js (vX.Y.Z) is not supported. Please upgrade to Node.js v18.19.0 or higher."},{"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.","cause":"`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`.","error":"TypeError: Cannot read properties of undefined (reading 'mockService') (or similar for other app.mock* methods)"},{"fix":"Add `afterEach(mm.restore);` to your test suite to reset all mocks after every test runs, ensuring isolation.","cause":"Missing `mm.restore()` call after each test, which prevents cleanup of global mocks or mocked application state.","error":"Test suite fails inconsistently, with data from one test affecting others."},{"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.","cause":"Incorrect module import syntax (e.g., trying to use `require` in an ESM module or vice-versa, or incorrect named/default import).","error":"ReferenceError: mm is not defined"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":""}