Jest Mock Server

0.1.0 · active · verified Tue Apr 21

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

Warnings

Install

Imports

Quickstart

Demonstrates setting up a mock server, defining a dynamic route with Koa context, and asserting calls using Jest API with an HTTP client.

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);
  });
});

view raw JSON →