Spy4js Testing Spy Framework

5.0.0 · active · verified Sun Apr 19

Spy4js is a standalone JavaScript and TypeScript testing spy framework designed for integration with test runners like Vitest and Jest. It provides a robust API for creating and managing spies, focusing on test readability, detailed error messages, and efficient serialization of call arguments. The package aims to offer an intuitive alternative or supplement to the built-in spying capabilities of popular test frameworks. The current stable version is 5.0.0, released in September 2025. While release cadence can be irregular, significant updates (like the TypeScript migration in v3.0.0) introduce notable breaking changes. Key differentiators include an API optimized for readability, enhanced error reporting with detailed comparisons, and features like customizable behavior and module mocking capabilities for both CommonJS and ES Modules.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates initializing a spy, simulating calls, and performing basic assertions like checking call count and arguments, and mocking an existing object's method.

import { Spy } from 'spy4js';

// Initialize a basic spy
const mySpy = Spy('myFunctionSpy');

// Simulate calling the spy
mySpy(1, 2, 'hello');
mySpy({ data: 'test' });

// Assertions
if (!mySpy.wasCalled()) {
  throw new Error('mySpy was not called!');
}

if (!mySpy.wasCalledWith(1, 2, 'hello')) {
  throw new Error('mySpy was not called with expected arguments!');
}

if (mySpy.getCallCount() !== 2) {
  throw new Error(`Expected 2 calls, got ${mySpy.getCallCount()}`);
}

console.log('Spy calls:', mySpy.getAllCallArguments());

// Mock an existing object's method
const service = { 
  getData: (id: string) => `Data for ${id}`,
  process: () => 'done'
};
const getDataSpy = Spy.on(service, 'getData').returns('Mocked Data');

console.log(service.getData('123')); // Outputs: Mocked Data
if (!getDataSpy.wasCalledWith('123')) {
  throw new Error('getDataSpy was not called as expected!');
}

console.log('All good with spy4js!');

view raw JSON →