ThinkJS HTTP Mocking Utility
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
-
TypeError: mockHttp is not a function
cause Attempting to use `mockHttp` after importing it incorrectly, most commonly with a named import (`import { mockHttp } from 'think-mock-http';`) in an ESM context, or if the `require` statement fails in CJS.fixEnsure you are using a default import in ESM: `import mockHttp from 'think-mock-http';`. In CommonJS, use `const mockHttp = require('think-mock-http');`. -
ReferenceError: think is not defined
cause The `mockHttp` function requires an instance of the ThinkJS framework (`think` object) as its first argument, which was not provided or was undefined.fixWhen calling `mockHttp(think, { ... })`, ensure that `think` is a properly initialized instance of the ThinkJS application. In a test environment, this `think` object is typically provided by the ThinkJS test runner or needs to be stubbed minimally. -
Mocked request does not hit the expected ThinkJS controller/logic, or returns an unexpected response.
cause Incorrect configuration of the mock request `url`, `method`, `data`, or `header` options, or the stubbed `think` instance is missing critical properties that the ThinkJS routing/middleware expects.fixDouble-check the `url`, `method`, `data`, and `header` parameters passed to `mockHttp` to accurately reflect the actual request you intend to simulate. Ensure your `think` stub (if not a full ThinkJS instance) provides necessary configurations or methods that `think-mock-http` or your ThinkJS application's routing relies on.
Warnings
- gotcha The package specifies `engines.node: >=6.0.0`, which is an extremely old Node.js version. While it might still run on modern Node.js, it indicates a lack of testing against recent environments and potential incompatibilities with newer JavaScript features or Node.js APIs.
- gotcha The library exports primarily as CommonJS (`module.exports`). When used in an ES Modules (ESM) context, it must be imported as a default import (`import mockHttp from 'think-mock-http';`). Attempting a named import (`import { mockHttp } from 'think-mock-http';`) will result in an error.
- gotcha The package's last commit was in 2019, suggesting it is no longer actively developed for new features, only maintained for critical fixes if ThinkJS itself continues to rely on it. This could mean slower resolution of issues or lack of support for future ThinkJS architectural changes.
- gotcha This library is tightly coupled to the internal structure and API of ThinkJS 3.x. Compatibility with older (ThinkJS 2.x) or potential future major versions of ThinkJS is not guaranteed and would likely require updates to this package.
Install
-
npm install think-mock-http -
yarn add think-mock-http -
pnpm add think-mock-http
Imports
- mockHttp
import { mockHttp } from 'think-mock-http';import mockHttp from 'think-mock-http';
- mockHttp
const mockHttp = require('think-mock-http'); - MockHttpFunction (JSDoc type)
/** @typedef {import('think-mock-http')} MockHttpFunction */
Quickstart
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();