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

core-mocking.mddocs/

Core Mocking

Core mocking functionality for replacing object properties and function behavior with custom implementations. All mocked functions automatically include spy functionality for tracking calls.

Capabilities

Primary Mock Function

The main mocking function that replaces any property on any object with a custom value. When mocking functions, automatic spy instrumentation is added.

/**
 * Replace a property with a custom value and add spy functionality for functions
 * @param target - Object to mock property on
 * @param property - Property name to mock (string, symbol, or number)
 * @param value - Replacement value or function
 */
function mock(target: any, property: PropertyKey, value?: any): void;

Usage Examples:

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

// Mock with custom function
mm(fs, "readFileSync", () => "custom content");

// Mock with direct value
mm(process, "env", { NODE_ENV: "test" });

// Mock method with automatic spy tracking
const obj = { getData: async () => "real data" };
mm(obj, "getData", async () => "mock data");
console.log(await obj.getData()); // => "mock data"
console.log(obj.getData.called); // => 1

Alternative Call Patterns

The mock function can be accessed through multiple patterns. All patterns are equivalent and provide the same functionality:

// Via default export (proxy function)
function mm(target: any, property: PropertyKey, value?: any): void;

// Via named export  
function mock(target: any, property: PropertyKey, value?: any): void;

// Via named export alias
const mm: typeof mock; // Named export with same name as default

// Via property on default export
mm.mock(target: any, property: PropertyKey, value?: any): void;
mm.mm(target: any, property: PropertyKey, value?: any): void;

Usage Examples:

import mm, { mock, mm as mmNamed } from "mm";

// All these calls are equivalent:
mm(fs, "readFileSync", mockFn);        // Default export as function
mock(fs, "readFileSync", mockFn);      // Named export
mmNamed(fs, "readFileSync", mockFn);   // Named export alias
mm.mock(fs, "readFileSync", mockFn);   // Property access
mm.mm(fs, "readFileSync", mockFn);     // Alternative property access

// Import flexibility examples
import mm from "mm";                    // Default only
import { mock } from "mm";              // Named only
import { mm as mockFn } from "mm";      // Named with alias
import mm, { mock } from "mm";          // Mixed import

Mock Status Checking

Check whether a property is currently mocked.

/**
 * Check if a property is currently mocked
 * @param target - Object to check
 * @param property - Property name to check
 * @returns True if property is mocked, false otherwise
 */
function isMocked(target: any, property: PropertyKey): boolean;

Usage Examples:

import fs from "node:fs";
import { isMocked } from "mm";

console.log(isMocked(fs, "readFileSync")); // => false

mm(fs, "readFileSync", () => "mock");
console.log(isMocked(fs, "readFileSync")); // => true

Mock Restoration

Restore all mocked properties to their original values and clean up spy instrumentation.

/**
 * Restore all mocked properties to their original state
 * Removes all spy instrumentation and resets call tracking
 */
function restore(): void;

Usage Examples:

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

mm(fs, "readFileSync", () => "mock content");
console.log(fs.readFileSync("file.txt")); // => "mock content"

mm.restore();
console.log(fs.readFileSync("file.txt")); // Throws real file system error

Automatic Spy Instrumentation

When mocking functions, mm automatically adds spy properties to track function calls:

interface SpyProperties {
  /** Number of times the function has been called */
  called: number;
  /** Array containing the arguments from each function call */
  calledArguments: any[][];
  /** Arguments from the most recent function call */
  lastCalledArguments: any[];
}

Usage Examples:

import mm from "mm";

const api = {
  fetchUser: async (id: string) => ({ id, name: "Real User" })
};

mm(api, "fetchUser", async (id: string) => ({ id, name: "Mock User" }));

await api.fetchUser("123");
await api.fetchUser("456");

console.log(api.fetchUser.called); // => 2
console.log(api.fetchUser.calledArguments); // => [["123"], ["456"]]
console.log(api.fetchUser.lastCalledArguments); // => ["456"]

Jest Mock Function Compatibility

mm recognizes and preserves Jest mock functions without adding duplicate spy instrumentation. When a Jest mock function is detected (via _isMockFunction property and mock object), mm skips adding its own spy wrapper.

import mm from "mm";
import { jest } from "@jest/globals";

const mockFn = jest.fn(() => "jest mock");
mm(someObject, "method", mockFn);

// Jest's native mock properties are preserved and work normally
console.log(mockFn.mock.calls.length);
console.log(mockFn.mock.results);
console.log(mockFn.mock.instances);

// mm does not add conflicting spy properties when Jest mocks are used
// The function retains Jest's original behavior and tracking

Usage Examples:

import { jest } from "@jest/globals";
import mm from "mm";

const api = {
  fetchData: async () => "real data"
};

// Using Jest mock with mm
const jestMock = jest.fn().mockResolvedValue("jest mock data");
mm(api, "fetchData", jestMock);

await api.fetchData();

// Use Jest's assertions and properties
expect(jestMock).toHaveBeenCalledTimes(1);
expect(jestMock.mock.calls).toEqual([[]]);

// Mixed usage - some functions with Jest mocks, others with mm
const logMock = jest.fn();
mm(console, "log", logMock);
mm(api, "getData", () => "mm mock"); // Regular mm mock with spy properties

console.log("test");
api.getData();

expect(logMock).toHaveBeenCalledWith("test");
console.log(api.getData.called); // => 1 (mm spy properties)

Async Function Type Safety

mm enforces type safety between async and sync function mocking to prevent runtime errors:

const obj = {
  asyncMethod: async () => "async result"
};

// This will work
mm(obj, "asyncMethod", async () => "mock result");

// This will throw an error at runtime
mm(obj, "asyncMethod", () => "sync result"); // Error: Can't mock async function to normal function

Types

// 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[];
}

docs

async-mocking.md

core-mocking.md

http-mocking.md

index.md

spy-functions.md

sync-mocking.md

system-mocking.md

tile.json