Simple, intuitive mocking of Node.js modules for testing purposes.
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Mock Require provides simple, intuitive mocking of Node.js modules for testing purposes. It allows you to replace any required module (local files, external modules, or built-in modules) with custom implementations, making it ideal for unit testing and test isolation.
npm install mock-requireconst mock = require('mock-require');const mock = require('mock-require');
// Mock a module with a custom implementation
mock('fs', {
readFileSync: function() {
return 'mocked content';
}
});
// Use the mocked module
const fs = require('fs');
console.log(fs.readFileSync()); // 'mocked content'
// Stop mocking when done
mock.stop('fs');Replace any module with a custom implementation or redirect to another module.
/**
* Mock a module with custom implementation or redirect to another module
* @param {string} path - Module path to mock (same as require() path)
* @param {*} mockExport - Mock implementation (any value) or path to replacement module (string)
*/
function mock(path, mockExport);Usage Examples:
const mock = require('mock-require');
// Mock with custom object
mock('http', {
request: function() {
console.log('http.request called');
}
});
// Mock with custom function
mock('./utils', function() {
return 'mocked utility';
});
// Redirect one module to another
mock('fs', 'path'); // require('fs') will return require('path')
// Mock non-existent modules
mock('fake-module', { fake: true });Supported Mock Types:
Remove the mock for a specific module, restoring its original behavior.
/**
* Stop mocking a specific module
* @param {string} path - Module path to stop mocking
*/
mock.stop(path);Usage Example:
const mock = require('mock-require');
mock('./module', { mocked: true });
const mockVersion = require('./module');
mock.stop('./module');
const realVersion = require('./module');
// mockVersion !== realVersionRemove all registered mocks without the need to stop them individually.
/**
* Remove all registered mocks
*/
mock.stopAll();Usage Example:
const mock = require('mock-require');
mock('fs', {});
mock('path', {});
mock('http', {});
// Clean up all mocks at once
mock.stopAll();Clear Node.js require cache for a module and require it again, useful for applying mocks to already-cached modules.
/**
* Clear require cache and re-require a module
* @param {string} path - Module path to refresh from cache
* @returns {*} The freshly required module
*/
mock.reRequire(path);Usage Example:
const mock = require('mock-require');
// Module is already cached
const fs = require('fs');
const fileToTest = require('./fileToTest');
// Apply mock after initial require
mock('fs', { mocked: true });
// Re-require to apply the mock
const updatedFileToTest = mock.reRequire('./fileToTest');
// updatedFileToTest now uses the mocked fsMock Require intelligently handles different types of module paths:
./file.js, ../utils/helper.js - Resolved relative to the calling filelodash, express - Resolved from node_modulesfs, http, path - Node.js core modulesPath Resolution Behavior:
normalize-path for cross-platform compatibilitymock(), not the current working directoryMocks can depend on other mocks, creating a cascade effect:
mock('path', { mocked: true });
mock('fs', 'path'); // fs will use the mocked path
const fs = require('fs'); // Returns { mocked: true }Mock Require handles various error scenarios gracefully:
Module Not Found:
When you stop mocking a non-existent module, subsequent require attempts will throw the standard MODULE_NOT_FOUND error:
mock('non-existent-module', { fake: true });
mock.stop('non-existent-module');
try {
require('non-existent-module');
} catch (e) {
console.log(e.code); // 'MODULE_NOT_FOUND'
}Perfect for test scenarios where you need to isolate dependencies:
// In test setup
afterEach(() => {
mock.stopAll(); // Clean up all mocks between tests
});
it('should handle file operations', () => {
mock('fs', {
readFileSync: () => 'test content',
writeFileSync: () => {}
});
// Test code that uses fs
const result = myFunction();
assert.equal(result, 'expected');
});