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

sync-mocking.mddocs/

Synchronous Function Mocking

Direct mocking capabilities for synchronous functions with immediate return values or error throwing. Perfect for testing pure functions, synchronous APIs, and blocking operations.

Capabilities

Mock Synchronous Data Return

Mock synchronous functions to return specific data immediately.

/**
 * Mock synchronous function to return data immediately
 * @param mod - Object containing the method to mock
 * @param method - Method name to mock
 * @param data - Data to return (optional, defaults to undefined)
 */
function syncData(mod: any, method: string | symbol, data?: any): void;

Usage Examples:

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

// Mock with specific data
syncData(fs, "readFileSync", Buffer.from("mocked file content"));
const content = fs.readFileSync("any-file.txt");
console.log(content); // => Buffer("mocked file content")

// Mock with object data
const config = { get: (key: string) => "real value" };
syncData(config, "get", "mock value");
console.log(config.get("any-key")); // => "mock value"

// Mock with complex data structures
const parser = { parseXML: (xml: string) => ({ error: "real parsing" }) };
syncData(parser, "parseXML", { data: { users: [{ id: 1, name: "Mock User" }] } });

Mock Synchronous Empty Return

Mock synchronous functions to return undefined immediately.

/**
 * Mock synchronous function to return undefined
 * @param mod - Object containing the method to mock
 * @param method - Method name to mock
 */
function syncEmpty(mod: any, method: string | symbol): void;

Usage Examples:

import { syncEmpty } from "mm";

// Mock void functions
const logger = { 
  log: (message: string) => console.log(`[LOG] ${message}`)
};

syncEmpty(logger, "log");
logger.log("This won't be printed"); // Returns undefined, no output

// Mock functions that should do nothing
const cache = { 
  clear: () => { /* complex clearing logic */ }
};

syncEmpty(cache, "clear");
cache.clear(); // Does nothing, returns undefined

Mock Synchronous Errors

Mock synchronous functions to throw errors immediately.

/**
 * Mock synchronous function to throw error immediately
 * @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 (optional)
 */
function syncError(mod: any, method: string | symbol, error?: MockError, props?: Record<string, any>): void;

type MockError = Error | string;

Usage Examples:

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

// Mock with simple error message
syncError(fs, "readFileSync", "File not found");
try {
  fs.readFileSync("missing.txt");
} catch (err) {
  console.log(err.message); // => "File not found"
  console.log(err.name); // => "MockError"
}

// Mock with custom Error instance
const customError = new Error("Permission denied");
syncError(fs, "readFileSync", customError);

// Mock with error properties
syncError(fs, "readFileSync", "Access denied", { 
  code: "EACCES", 
  errno: -13,
  path: "/restricted/file.txt"
});

try {
  fs.readFileSync("/restricted/file.txt");
} catch (err) {
  console.log(err.code); // => "EACCES"
  console.log(err.errno); // => -13
  console.log(err.path); // => "/restricted/file.txt"
}

Default Error Creation

When no error is provided, mm creates a default error:

import { syncError } from "mm";

// No error provided - creates default
syncError(someObject, "method");

try {
  someObject.method();
} catch (err) {
  console.log(err.message); // => "mm mock error"
  console.log(err.name); // => "MockError"
}

Synchronous vs Asynchronous Considerations

Synchronous mocks are ideal for:

  • Pure functions: Functions that don't perform I/O operations
  • Data transformations: Parsing, formatting, validation functions
  • Configuration access: Getting settings, environment variables
  • Synchronous APIs: File system sync operations, crypto functions
  • Testing error conditions: Immediate error simulation

Usage Examples:

import crypto from "node:crypto";
import { syncData, syncError } from "mm";

// Mock crypto operations
syncData(crypto, "randomBytes", Buffer.from("mock-random-data"));
const mockRandom = crypto.randomBytes(16); // Deterministic for testing

// Mock parsing functions
const jsonParser = { 
  parse: (str: string) => JSON.parse(str) 
};

syncError(jsonParser, "parse", "Invalid JSON", { 
  position: 42 
});

try {
  jsonParser.parse("invalid json");
} catch (err) {
  console.log(err.position); // => 42
}

Integration with Spy Functionality

All synchronous mocks automatically include spy properties for call tracking:

import { syncData } from "mm";

const calculator = {
  multiply: (a: number, b: number) => a * b
};

syncData(calculator, "multiply", 42);

const result1 = calculator.multiply(3, 4); // => 42
const result2 = calculator.multiply(7, 8); // => 42

console.log(calculator.multiply.called); // => 2
console.log(calculator.multiply.calledArguments); // => [[3, 4], [7, 8]]
console.log(calculator.multiply.lastCalledArguments); // => [7, 8]

Error Types and Properties

Synchronous error mocking supports rich error information:

import { syncError } from "mm";

const validator = {
  validate: (data: any) => { /* validation logic */ }
};

// Mock validation error with detailed information
syncError(validator, "validate", "Validation failed", {
  field: "email",
  code: "INVALID_FORMAT",
  value: "not-an-email",
  expected: "Valid email address"
});

try {
  validator.validate({ email: "not-an-email" });
} catch (err) {
  console.log(err.field); // => "email"
  console.log(err.code); // => "INVALID_FORMAT"
  console.log(err.value); // => "not-an-email"
  console.log(err.expected); // => "Valid email address"
}

Types

// Error types for synchronous 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