CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-mm

Mock mate library for mocking functions, HTTP requests, and file system operations in Node.js testing

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

mm (Mock Mate)

mm is a flexible and comprehensive mocking library for Node.js testing environments. It provides extensive capabilities for mocking functions, HTTP/HTTPS requests, child processes, and class methods with built-in spy functionality and automatic call tracking.

Package Information

  • Package Name: mm
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install mm --save-dev

Core Imports

ESM:

// Default import (proxy function)
import mm from "mm";

// Named imports
import { mock, restore, spy, data, error, mm as mmNamed } from "mm";

// Mixed imports
import mm, { restore, spy } from "mm";

// Namespace imports
import * as mockMate from "mm";

CommonJS:

// Default import
const mm = require("mm");

// Named imports  
const { mock, restore, spy, data, error, mm: mmNamed } = require("mm");

// Mixed imports
const mm = require("mm");
const { restore, spy } = require("mm");

Basic Usage

import fs from "node:fs";
import mm from "mm";

// Mock a function to return specific data
mm.data(fs, "readFileSync", "mocked file content");
console.log(fs.readFileSync("any-file.txt")); // => "mocked file content"

// Mock a function to throw an error
mm.error(fs, "readFile", "Mock error message");

// Spy on a function (track calls without changing behavior)
const obj = { calculate: (a, b) => a + b };
mm.spy(obj, "calculate");
obj.calculate(2, 3); // Returns 5, but also tracks the call
console.log(obj.calculate.called); // => 1
console.log(obj.calculate.lastCalledArguments); // => [2, 3]

// Restore all mocks
mm.restore();

Architecture

mm is built around several key components:

  • Core Mocking Engine: Proxy-based function replacement with automatic spy instrumentation
  • Async/Sync Support: Handles callbacks, promises, generators, and synchronous functions
  • HTTP Request Mocking: Complete HTTP/HTTPS request and response simulation
  • Call Tracking: Built-in spy functionality with detailed call history
  • Resource Management: Modern JavaScript features like Symbol.asyncDispose support
  • Restoration System: Clean teardown of all mocks and spies

Capabilities

Core Function Mocking

Basic mocking functionality for replacing function behavior with custom implementations, error simulation, or data returns.

// Default export - proxy function (can be called directly)
function mm(target: any, property: PropertyKey, value?: any): void;

// Named export - explicit mock function
function mock(target: any, property: PropertyKey, value?: any): void;

// Alternative access patterns (all equivalent)
mm.mock(target: any, property: PropertyKey, value?: any): void;
mm.mm(target: any, property: PropertyKey, value?: any): void;

// Check if a property is mocked
function isMocked(target: any, property: PropertyKey): boolean;

// Restore all mocks
function restore(): void;

Core Mocking

Asynchronous Function Mocking

Comprehensive mocking for async functions, callbacks, promises, and generators with timeout and error simulation support.

// Mock async function to return data (with alias)
function mockData(mod: any, method: string | symbol, data: any, timeout?: number): void;
function data(mod: any, method: string | symbol, data: any, timeout?: number): void; // alias

// Mock async function to return multiple data arguments (with alias)
function mockDatas(mod: any, method: string | symbol, datas: any[] | any, timeout?: number): void;
function datas(mod: any, method: string | symbol, datas: any[] | any, timeout?: number): void; // alias

// Mock async function to return empty response (with alias)
function mockEmpty(mod: any, method: string | symbol, timeout?: number): void;
function empty(mod: any, method: string | symbol, timeout?: number): void; // alias

// Mock async function to return error (with alias)
function mockError(mod: any, method: string | symbol, error?: MockError, props?: Record<string, any> | number, timeout?: number): void;
function error(mod: any, method: string | symbol, error?: MockError, props?: Record<string, any> | number, timeout?: number): void; // alias

// Mock async function to return error once
function errorOnce(mod: any, method: string | symbol, error?: MockError, props?: Record<string, any> | number, timeout?: number): void;

// Mock with Symbol.asyncDispose support
function dataWithAsyncDispose(mod: any, method: string | symbol, data: any, timeout?: number): void;

Async Mocking

Synchronous Function Mocking

Direct mocking for synchronous functions with immediate return values or error throwing.

// Mock sync function to return data
function syncData(mod: any, method: string | symbol, data?: any): void;

// Mock sync function to throw error
function syncError(mod: any, method: string | symbol, error?: MockError, props?: Record<string, any>): void;

Sync Mocking

HTTP Request Mocking

Mock HTTP and HTTPS requests with custom responses, headers, and error simulation for testing network-dependent code.

// Direct function imports
function mockHttpRequest(url: RequestURL, data: ResponseData, headers?: Record<string, any>, delay?: number): void;
function mockHttpsRequest(url: RequestURL, data: ResponseData, headers?: Record<string, any>, delay?: number): void;
function mockHttpRequestError(url: RequestURL, reqError?: MockError, resError?: MockError, delay?: number): void;
function mockHttpsRequestError(url: RequestURL, reqError?: MockError, resError?: MockError, delay?: number): void;

// Namespace access patterns
mm.http.request(url: RequestURL, data: ResponseData, headers?: Record<string, any>, delay?: number): void;
mm.http.requestError(url: RequestURL, reqError?: MockError, resError?: MockError, delay?: number): void;
mm.https.request(url: RequestURL, data: ResponseData, headers?: Record<string, any>, delay?: number): void;
mm.https.requestError(url: RequestURL, reqError?: MockError, resError?: MockError, delay?: number): void;

// Named export access  
http.request(url: RequestURL, data: ResponseData, headers?: Record<string, any>, delay?: number): void;
https.request(url: RequestURL, data: ResponseData, headers?: Record<string, any>, delay?: number): void;

type RequestURL = string | RegExp | URL | object;
type ResponseData = string | Buffer | Readable;

HTTP Mocking

Spy Functionality

Track function calls without changing their behavior, including call counts and argument history.

// Create a spy that tracks calls without changing behavior
function spy(mod: any, method: string | symbol): void;

// Mock class methods affecting all instances
function classMethod(instance: any, property: PropertyKey, value?: any): void;

When functions are mocked, they automatically gain spy properties:

interface SpyProperties {
  called: number;                    // Number of times called
  calledArguments: any[][];         // All call arguments
  lastCalledArguments: any[];       // Most recent call arguments
}

Spy Functions

Process and System Mocking

Mock child processes and system operations for testing command-line interactions and process spawning.

// Mock child_process.spawn
function spawn(code: number, stdout: string, stderr: string, timeout?: number): void;

System Mocking

Types

// Error types for mocking
type MockError = Error | string;

// HTTP mocking types
type RequestURL = string | RegExp | URL | object;
type ResponseData = string | Buffer | Readable;

// Property key types for mocking
type PropertyKey = string | number | symbol;

// Spy properties automatically added to mocked functions
interface SpyProperties {
  called: number;
  calledArguments: any[][];
  lastCalledArguments: any[];
}

// HTTP namespace interfaces
interface HttpMockNamespace {
  request: typeof mockHttpRequest;
  requestError: typeof mockHttpRequestError;
}

interface HttpsMockNamespace {
  request: typeof mockHttpsRequest;
  requestError: typeof mockHttpsRequestError;
}

// Main mm object interface (default export)
interface MmInstance {
  // Callable as function
  (target: any, property: PropertyKey, value?: any): void;
  
  // Core methods
  mock: typeof mock;
  mm: typeof mock;
  isMocked: typeof isMocked;
  restore: typeof restore;
  
  // Async methods
  data: typeof mockData;
  mockData: typeof mockData;
  datas: typeof mockDatas;
  mockDatas: typeof mockDatas;
  empty: typeof mockEmpty;
  mockEmpty: typeof mockEmpty;
  error: typeof mockError;
  mockError: typeof mockError;
  errorOnce: typeof errorOnce;
  dataWithAsyncDispose: typeof dataWithAsyncDispose;
  
  // Sync methods
  syncData: typeof syncData;
  syncEmpty: typeof syncEmpty;
  syncError: typeof syncError;
  
  // Spy methods
  spy: typeof spy;
  classMethod: typeof classMethod;
  
  // HTTP namespaces
  http: HttpMockNamespace;
  https: HttpsMockNamespace;
  
  // System methods
  spawn: typeof spawn;
}

Error Handling

mm provides several error simulation patterns:

  • Async errors: Via callback with mockError() and errorOnce()
  • Sync errors: Immediate throwing with syncError()
  • HTTP errors: Request/response error simulation with http.requestError() and https.requestError()
  • Custom error properties: Additional error metadata via props parameter
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/mm@4.0.x
Publish Source
CLI
Badge
tessl/npm-mm badge