or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-mock-require

Simple, intuitive mocking of Node.js modules for testing purposes.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/mock-require@3.0.x

To install, run

npx @tessl/cli install tessl/npm-mock-require@3.0.0

index.mddocs/

Mock Require

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.

Package Information

  • Package Name: mock-require
  • Package Type: npm
  • Language: JavaScript (CommonJS)
  • Installation: npm install mock-require

Core Imports

const mock = require('mock-require');

Basic Usage

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');

Capabilities

Mock Module

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:

  • Objects: Custom object implementations
  • Functions: Function replacements
  • Strings: Path to another module to use as replacement
  • Any Value: Primitives, arrays, null, undefined, or any JavaScript value

Stop Mocking

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 !== realVersion

Stop All Mocking

Remove 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();

Re-require Module

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 fs

Advanced Features

Path Resolution

Mock Require intelligently handles different types of module paths:

  • Local modules: ./file.js, ../utils/helper.js - Resolved relative to the calling file
  • External modules: lodash, express - Resolved from node_modules
  • Built-in modules: fs, http, path - Node.js core modules
  • Node path modules: Modules in NODE_PATH environment variable
  • Non-existent modules: Modules that don't exist in the filesystem can still be mocked

Path Resolution Behavior:

  • Paths are normalized using normalize-path for cross-platform compatibility
  • Local modules are resolved relative to the file calling mock(), not the current working directory
  • External and built-in modules are resolved using Node's standard resolution algorithm
  • Non-existent local modules can be mocked and will be resolved to their expected path

Cascade Mocking

Mocks 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 }

Error Handling

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'
}

Test Isolation

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');
});