Node.js Legacy Mock Modules (vojtajina/node-mocks)
The `mocks` package (npm: `mocks`), version 0.0.15, is an abandoned Node.js library initially created to provide basic mock implementations for the built-in `fs` (file system) and `http` modules for unit testing. Last published in August 2013, this package targets extremely old Node.js versions (specifically `>= 0.6.5`), which corresponds to Node.js releases from 2011-2012. The API provided is a very limited subset of the actual Node.js `fs` and `http` functionalities, having been developed primarily to support the testing needs of `Testacular` (now known as Karma). Given its lack of updates for over a decade, it does not support modern JavaScript features like ESM, contemporary Node.js APIs, or TypeScript type definitions. Developers should consider modern, actively maintained alternatives such as `mock-fs` for file system mocking, `node-mocks-http` or `nock` for HTTP requests, and general-purpose testing frameworks with robust mocking capabilities.
Common errors
-
SyntaxError: Cannot use import statement outside a module
cause Attempting to use ES Module `import` syntax with the CommonJS-only `mocks` package.fixChange `import mocks from 'mocks';` to `const mocks = require('mocks');` and ensure your environment supports CommonJS. -
TypeError: fs.someUnsupportedMethod is not a function
cause Attempting to call an `fs` or `http` method that is not implemented by the `mocks` package.fixConsult the `mocks` package's GitHub repository for the limited list of supported methods. For broader API support, consider modern alternatives like `mock-fs` or `nock`. -
Error: Cannot find module 'mocks'
cause The package is not installed or the Node.js runtime cannot resolve its path.fixEnsure the package is installed via `npm install mocks` or `yarn add mocks` and that your Node.js resolution paths are correctly configured. Verify that `node_modules` is accessible.
Warnings
- breaking The `mocks` package is officially abandoned and has not been updated since August 2013. It is not compatible with modern Node.js versions or ES Modules, and its APIs are severely outdated and incomplete compared to current Node.js built-ins.
- gotcha The mock `fs` and `http` modules provided by this package implement only a very small subset of the actual Node.js APIs. Many common `fs` or `http` methods will be missing or have incomplete implementations, leading to unexpected runtime errors during testing.
- gotcha This package is written exclusively in CommonJS and does not provide ES Module (ESM) entry points. Attempting to `import` it will result in a `SyntaxError` in ESM contexts.
- gotcha There are no TypeScript type definitions available for the `mocks` package. Using it in a TypeScript project will result in type errors and lack of autocomplete, requiring manual type declarations.
Install
-
npm install mocks -
yarn add mocks -
pnpm add mocks
Imports
- mocks
import mocks from 'mocks';
const mocks = require('mocks'); - mocks.fs
const fs = require('fs'); // This loads the real fs module unless patched differentlyconst fs = require('mocks').fs; - mocks.http
const http = require('http'); // This loads the real http moduleconst http = require('mocks').http;
Quickstart
const mocks = require('mocks');
const fs = mocks.fs; // Get the mocked fs module
const http = mocks.http; // Get the mocked http module
// Configure the mock file system with files and directories
fs._set('/app/data/config.json', JSON.stringify({ version: '1.0.0', enabled: true }));
fs._set('/app/logs', {}); // Mock an empty directory
fs._set('/app/src/main.js', 'console.log("Hello from mocked file!");');
console.log('--- Mocking File System ---');
// Simulate reading a file synchronously
try {
const configContent = fs.readFileSync('/app/data/config.json', 'utf8');
console.log('Read config.json:', configContent);
const config = JSON.parse(configContent);
console.log('Parsed config version:', config.version);
} catch (e) {
console.error('Error reading config.json:', e.message);
}
// Simulate reading a non-existent file
try {
fs.readFileSync('/app/data/nonexistent.txt');
} catch (e) {
console.log('Expected error for non-existent file:', e.message);
}
console.log('\n--- Mocking HTTP Request/Response ---');
// Mock an HTTP server request and response for testing a handler
const mockRequest = new http.ServerRequest({
url: '/api/items/123',
method: 'GET',
headers: { 'Accept': 'application/json', 'User-Agent': 'MockTest' }
});
const mockResponse = new http.ServerResponse();
mockResponse.statusCode = 200;
mockResponse.setHeader('Content-Type', 'application/json');
mockResponse.end(JSON.stringify({ id: '123', name: 'Mock Item' }));
console.log('Mock HTTP Request URL:', mockRequest.url);
console.log('Mock HTTP Request Method:', mockRequest.method);
console.log('Mock HTTP Response Status Code:', mockResponse.statusCode);
console.log('Mock HTTP Response Headers:', mockResponse.getHeaders());
console.log('Mock HTTP Response Body:', mockResponse._getData().toString()); // _getData() retrieves the buffered response