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

async-mocking.mddocs/

Asynchronous Function Mocking

Comprehensive mocking capabilities for asynchronous functions including callback-based functions, promises, async/await, and generator functions. All async mocks support timeout simulation and automatic spy tracking.

Capabilities

Mock Data Return

Mock asynchronous functions to return specific data via callback or promise resolution.

/**
 * Mock async function to return data via callback(null, data) or promise resolution
 * @param mod - Object containing the method to mock
 * @param method - Method name to mock
 * @param data - Data to return
 * @param timeout - Optional delay in milliseconds (default: 0)
 */
function mockData(mod: any, method: string | symbol, data: any, timeout?: number): void;

// Alias available
function data(mod: any, method: string | symbol, data: any, timeout?: number): void;

Usage Examples:

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

// Mock callback-based function
mockData(fs, "readFile", "mocked file content");
fs.readFile("file.txt", "utf8", (err, data) => {
  console.log(err); // => null
  console.log(data); // => "mocked file content"
});

// Mock async function with timeout
const api = {
  fetchUser: async (id: string) => ({ id, name: "Real User" })
};
mockData(api, "fetchUser", { id: "123", name: "Mock User" }, 100);
const user = await api.fetchUser("123"); // Resolves after 100ms

Mock Multiple Data Arguments

Mock asynchronous functions to return multiple arguments via callback or promise.

/**
 * Mock async function to return multiple data arguments via callback(null, ...datas)
 * @param mod - Object containing the method to mock
 * @param method - Method name to mock  
 * @param datas - Array of data arguments to return, or single value
 * @param timeout - Optional delay in milliseconds (default: 0)
 */
function mockDatas(mod: any, method: string | symbol, datas: any[] | any, timeout?: number): void;

// Alias available
function datas(mod: any, method: string | symbol, datas: any[] | any, timeout?: number): void;

Usage Examples:

import { mockDatas } from "mm";

// Mock with multiple return values
const urllib = {
  request: (url: string, callback: (err: any, data: Buffer, headers: any) => void) => {}
};

mockDatas(urllib, "request", [Buffer.from("response data"), { "content-type": "text/plain" }]);
urllib.request("http://example.com", (err, data, headers) => {
  console.log(err); // => null
  console.log(data); // => Buffer("response data")  
  console.log(headers); // => { "content-type": "text/plain" }
});

// Single value (automatically wrapped in array for callbacks)
mockDatas(urllib, "request", Buffer.from("simple response"));

Mock Empty Response

Mock asynchronous functions to return callback(null, null) or resolve with undefined.

/**
 * Mock async function to return empty response via callback(null, null)
 * @param mod - Object containing the method to mock
 * @param method - Method name to mock
 * @param timeout - Optional delay in milliseconds (default: 0)
 */
function mockEmpty(mod: any, method: string | symbol, timeout?: number): void;

// Alias available  
function empty(mod: any, method: string | symbol, timeout?: number): void;

Usage Examples:

import { mockEmpty } from "mm";

const mysql = {
  query: (sql: string, callback: (err: any, results?: any) => void) => {}
};

mockEmpty(mysql, "query");
mysql.query("DELETE FROM users", (err, results) => {
  console.log(err); // => null
  console.log(results); // => null
});

Mock Errors

Mock asynchronous functions to return errors via callback or promise rejection.

/**
 * Mock async function to return error via callback or promise rejection
 * @param mod - Object containing the method to mock
 * @param method - Method name to mock
 * @param error - Error message string or Error instance (optional)
 * @param props - Additional error properties or timeout if number (optional)
 * @param timeout - Delay in milliseconds (optional)
 */
function mockError(mod: any, method: string | symbol, error?: MockError, props?: Record<string, any> | number, timeout?: number): void;

// Alias available
function error(mod: any, method: string | symbol, error?: MockError, props?: Record<string, any> | number, timeout?: number): void;

type MockError = Error | string;

Usage Examples:

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

// Mock with simple error message
mockError(fs, "readFile", "File not found");
fs.readFile("missing.txt", (err, data) => {
  console.log(err.message); // => "File not found"
  console.log(err.name); // => "MockError"
});

// Mock with Error instance and custom properties
const customError = new Error("Permission denied");
mockError(fs, "readFile", customError, { code: "EACCES", errno: -13 });

// Mock with timeout (third parameter as number)
mockError(fs, "readFile", "Timeout error", 1000); // Error after 1 second

Mock Errors Once

Mock asynchronous functions to return an error once, then automatically restore the original behavior.

/**
 * Mock async function to return error once, then restore original behavior
 * @param mod - Object containing the method to mock
 * @param method - Method name to mock
 * @param error - Error message string or Error instance (optional)
 * @param props - Additional error properties or timeout if number (optional)  
 * @param timeout - Delay in milliseconds (optional)
 */
function errorOnce(mod: any, method: string | symbol, error?: MockError, props?: Record<string, any> | number, timeout?: number): void;

Usage Examples:

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

errorOnce(fs, "readFile", "Temporary failure");

// First call returns error
fs.readFile("file.txt", (err, data) => {
  console.log(err.message); // => "Temporary failure"
});

// Second call uses original function (no longer mocked)
fs.readFile("file.txt", (err, data) => {
  // Real file system behavior
});

Mock with AsyncDispose Support

Mock data with Symbol.asyncDispose support for modern JavaScript resource management patterns.

/**
 * Mock data with Symbol.asyncDispose support for resource management
 * @param mod - Object containing the method to mock
 * @param method - Method name to mock
 * @param data - Data to return (will be enhanced with asyncDispose)
 * @param timeout - Optional delay in milliseconds (default: 0)
 */
function dataWithAsyncDispose(mod: any, method: string | symbol, data: any, timeout?: number): void;

Usage Examples:

import { dataWithAsyncDispose } from "mm";

const locker = {
  tryLock: async (key: string) => ({ locked: false })
};

dataWithAsyncDispose(locker, "tryLock", { locked: true });

// Use with await using for automatic resource cleanup
await using lock = await locker.tryLock("resource-key");
console.log(lock.locked); // => true
// lock automatically disposed when leaving scope

Function Type Support

mm handles different asynchronous function patterns automatically:

Callback Functions

Traditional Node.js callback pattern with (err, ...results):

import { mockData } from "mm";

const fs = require("fs");
mockData(fs, "readFile", "mock content");

fs.readFile("file.txt", "utf8", (err, data) => {
  // err = null, data = "mock content"
});

Promise/Async Functions

Modern promise-based and async/await functions:

import { mockData } from "mm";

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

mockData(api, "fetchData", "mock data");
const result = await api.fetchData(); // => "mock data"

Generator Functions

ES6 generator functions with yield support:

import { mockData } from "mm";

const service = {
  *processData() {
    yield "real processing";
    return "real result";
  }
};

mockData(service, "processData", "mock result");
const gen = service.processData();
const result = gen.next().value; // => "mock result"

Timeout and Delay

All async mocking functions support optional timeout parameters to simulate real-world delays:

// Simulate slow network request
mockData(api, "slowRequest", "delayed response", 2000); // 2 second delay

// Simulate timeout error  
mockError(api, "unreliableService", "Timeout", 5000); // Error after 5 seconds

Types

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

// Spy properties added to all 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