ThinkJS HTTP Mocking Utility

1.0.6 · maintenance · verified Wed Apr 22

The `think-mock-http` package provides a dedicated utility for simulating HTTP requests and responses within ThinkJS 3.x applications, primarily for testing purposes. Currently at version 1.0.6, the library offers a simple API to create mock contexts, allowing developers to test controllers, middleware, and services without requiring a live HTTP server. Given its last significant update in 2019, its release cadence is slow, existing mainly for maintenance within the ThinkJS ecosystem rather than active feature development. Its key differentiator is its deep integration with the ThinkJS core, ensuring compatibility with the framework's internal request/response lifecycle, unlike generic HTTP mocking libraries.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to create a mock HTTP request context for a ThinkJS application, pass it a stubbed ThinkJS instance, and retrieve the simulated response for testing controller logic.

import mockHttp from 'think-mock-http';

// A minimal stub for the 'think' object for demonstration purposes.
// In a real ThinkJS test, 'think' would be the actual ThinkJS instance
// provided by the ThinkJS test environment.
const mockThink = {
  // Simulate common ThinkJS methods or properties that think-mock-http might interact with
  config: (key) => {
    if (key === 'url_pathname_prefix') return '';
    return {};
  },
  app: {
    emit: (event, ...args) => console.log(`ThinkJS app event: ${event}`, args)
  },
  Logger: class MockLogger { log(...args) { console.log('Mock Logger:', ...args); } },
  Controller: class MockController {},
  Service: class MockService {},
};

async function runMockHttpRequest() {
  try {
    const http = await mockHttp(mockThink, { // Pass the ThinkJS instance (or stub)
      url: '/api/users/123?param=test', // The URL path to mock
      method: 'GET',
      // 'data' is typically for POST/PUT, but can be included for completeness
      data: { query: 'example' },
      header: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${process.env.TEST_AUTH_TOKEN ?? 'mock-token'}`, // Use env vars for secrets
        'User-Agent': 'MockTestAgent/1.0',
      },
      referrer: 'http://localhost/',
    }).run(); // Execute the mock request

    console.log('--- Mock HTTP Response ---');
    console.log('Status:', http.status);
    console.log('Body:', http.body);
    console.log('Headers:', http.header);
    console.log('Redirected:', http.redirected);

    // Example assertion (in a real test framework like Jest or Mocha)
    if (http.status === 200 && typeof http.body === 'string' && http.body.includes('Successfully')) {
      console.log('Mock test successful: Received expected data.');
    } else {
      console.error('Mock test failed: Unexpected response or status.');
    }

  } catch (error) {
    console.error('Error during mock HTTP request:', error);
  }
}

runMockHttpRequest();

view raw JSON →