Jest Mock Server
jest-mock-server is a JavaScript/TypeScript library designed to facilitate testing of HTTP clients within a Jest testing environment. It offers a unique approach by allowing developers to define HTTP request handlers using the familiar Koa API for context manipulation and response generation, while leveraging Jest's powerful assertion API for verifying interactions with the mock server. The current stable version is 0.1.0, indicating it is still in early development, and future releases may introduce breaking changes without strict adherence to semantic versioning. Its release cadence appears to be irregular, with small incremental updates. Key differentiators include its seamless integration with both Koa for handler definition and Jest for comprehensive assertion capabilities, making it particularly suitable for projects already using these technologies.
Common errors
-
TypeError: jest_mock_server_1.MockServer is not a constructor (or similar 'is not a function' error)
cause Attempting to use `MockServer` as a default import when it is a named export, or incorrect CommonJS `require` usage.fixFor ESM, use `import { MockServer } from 'jest-mock-server';`. For CommonJS, use `const { MockServer } = require('jest-mock-server');`. -
npm ERR! ERESOLVE unable to resolve dependency tree (or similar peer dependency warning/error)
cause The `jest` package, a required peer dependency, is either not installed or its version conflicts with the requirements of `jest-mock-server`.fixInstall Jest as a development dependency: `npm install --save-dev jest` or `yarn add -D jest`. If a version conflict persists, try `npm install --force` or `yarn add -D jest@<compatible-version>` after checking `jest-mock-server`'s peer dependency range.
Warnings
- gotcha The package explicitly switched its minimum supported Node.js version to v14 in `v0.0.4`. While newer Node.js versions are likely compatible, projects running on Node.js versions older than 14 are not supported.
- gotcha `jest-mock-server` declares `jest` as a peer dependency. If Jest is not installed in your project, or if there's a significant version mismatch, it may lead to runtime errors or unexpected behavior.
- gotcha As `jest-mock-server` is currently in a `0.x.x` version series, it does not strictly adhere to semantic versioning. This means that breaking changes may be introduced in minor or patch releases without a major version bump, potentially causing unexpected issues upon upgrade.
Install
-
npm install jest-mock-server -
yarn add jest-mock-server -
pnpm add jest-mock-server
Imports
- MockServer
import MockServer from 'jest-mock-server';
import { MockServer } from 'jest-mock-server'; - MockServer (CommonJS)
const MockServer = require('jest-mock-server'); // Incorrectly assumes a default export for the entire moduleconst { MockServer } = require('jest-mock-server'); - Route definitions (type)
import type { Context } from 'koa';
Quickstart
import { MockServer } from 'jest-mock-server';
import fetch from 'node-fetch'; // Or any other http client like axios
describe('Testing HTTP client with jest-mock-server', () => {
const server = new MockServer();
// Start and stop the mock server for each test suite
beforeAll(() => server.start());
afterAll(() => server.stop());
// Reset routes before each test to ensure isolation
beforeEach(() => server.reset());
it('handles multiple requests with sequential responses', async () => {
// Define a GET route for the root path
const route = server
.get('/')
// Mock the first response to return status 200
.mockImplementationOnce((ctx) => {
ctx.status = 200;
ctx.body = 'First response';
})
// Mock the second response to return status 201
.mockImplementationOnce((ctx) => {
ctx.status = 201;
ctx.body = 'Second response';
});
// Get the URL where the server is listening (random free port by default)
const url = server.getURL();
// Make the first request
const res1 = await fetch(url);
expect(res1.status).toBe(200);
expect(await res1.text()).toBe('First response');
// Make the second request
const res2 = await fetch(url);
expect(res2.status).toBe(201);
expect(await res2.text()).toBe('Second response');
// Make a third request - since only two mocks were defined, it will return 404 by default
const res3 = await fetch(url);
expect(res3.status).toBe(404);
// Use Jest's assertion API to verify the route was called three times
expect(route).toHaveBeenCalledTimes(3);
});
});