{"id":16551,"library":"think-mock-http","title":"ThinkJS HTTP Mocking Utility","description":"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.","status":"maintenance","version":"1.0.6","language":"javascript","source_language":"en","source_url":"https://github.com/thinkjs/think-mock-http","tags":["javascript"],"install":[{"cmd":"npm install think-mock-http","lang":"bash","label":"npm"},{"cmd":"yarn add think-mock-http","lang":"bash","label":"yarn"},{"cmd":"pnpm add think-mock-http","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The library primarily uses CommonJS `module.exports = mockHttp`, which resolves as a default import in ESM. Avoid named imports.","wrong":"import { mockHttp } from 'think-mock-http';","symbol":"mockHttp","correct":"import mockHttp from 'think-mock-http';"},{"note":"Standard CommonJS import pattern for Node.js environments.","symbol":"mockHttp","correct":"const mockHttp = require('think-mock-http');"},{"note":"For type hinting with JSDoc in JavaScript projects, or when referencing the function type in TypeScript without explicit declaration files.","symbol":"MockHttpFunction (JSDoc type)","correct":"/** @typedef {import('think-mock-http')} MockHttpFunction */"}],"quickstart":{"code":"import mockHttp from 'think-mock-http';\n\n// A minimal stub for the 'think' object for demonstration purposes.\n// In a real ThinkJS test, 'think' would be the actual ThinkJS instance\n// provided by the ThinkJS test environment.\nconst mockThink = {\n  // Simulate common ThinkJS methods or properties that think-mock-http might interact with\n  config: (key) => {\n    if (key === 'url_pathname_prefix') return '';\n    return {};\n  },\n  app: {\n    emit: (event, ...args) => console.log(`ThinkJS app event: ${event}`, args)\n  },\n  Logger: class MockLogger { log(...args) { console.log('Mock Logger:', ...args); } },\n  Controller: class MockController {},\n  Service: class MockService {},\n};\n\nasync function runMockHttpRequest() {\n  try {\n    const http = await mockHttp(mockThink, { // Pass the ThinkJS instance (or stub)\n      url: '/api/users/123?param=test', // The URL path to mock\n      method: 'GET',\n      // 'data' is typically for POST/PUT, but can be included for completeness\n      data: { query: 'example' },\n      header: {\n        'Content-Type': 'application/json',\n        'Authorization': `Bearer ${process.env.TEST_AUTH_TOKEN ?? 'mock-token'}`, // Use env vars for secrets\n        'User-Agent': 'MockTestAgent/1.0',\n      },\n      referrer: 'http://localhost/',\n    }).run(); // Execute the mock request\n\n    console.log('--- Mock HTTP Response ---');\n    console.log('Status:', http.status);\n    console.log('Body:', http.body);\n    console.log('Headers:', http.header);\n    console.log('Redirected:', http.redirected);\n\n    // Example assertion (in a real test framework like Jest or Mocha)\n    if (http.status === 200 && typeof http.body === 'string' && http.body.includes('Successfully')) {\n      console.log('Mock test successful: Received expected data.');\n    } else {\n      console.error('Mock test failed: Unexpected response or status.');\n    }\n\n  } catch (error) {\n    console.error('Error during mock HTTP request:', error);\n  }\n}\n\nrunMockHttpRequest();\n","lang":"javascript","description":"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."},"warnings":[{"fix":"Ensure thorough testing in your target Node.js environment. Consider using nvm or Docker to test against older Node.js versions if issues arise.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Always use `import mockHttp from 'think-mock-http';` in ESM environments. For CommonJS, use `const mockHttp = require('think-mock-http');`.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Review the ThinkJS community and documentation for alternative or newer testing utilities if you encounter unaddressed issues or require features not present in this version. Pin the dependency to avoid unexpected breaking changes if a new major version were to ever be released.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Always test `think-mock-http` against your specific ThinkJS version. Consult ThinkJS documentation for compatible testing strategies.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Ensure you are using a default import in ESM: `import mockHttp from 'think-mock-http';`. In CommonJS, use `const mockHttp = require('think-mock-http');`.","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.","error":"TypeError: mockHttp is not a function"},{"fix":"When 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.","cause":"The `mockHttp` function requires an instance of the ThinkJS framework (`think` object) as its first argument, which was not provided or was undefined.","error":"ReferenceError: think is not defined"},{"fix":"Double-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.","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.","error":"Mocked request does not hit the expected ThinkJS controller/logic, or returns an unexpected response."}],"ecosystem":"npm"}