Registry / testing / spy4js

spy4js

JSON →
library5.0.0jsnpmunverified

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.

npm install spy4js
INSTALL
IMPORT
SIG · SPY4JS
S
spy4js
testingjavascriptv5.0.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Spy
import { Spy } from 'spy4js';
const Spy = require('spy4js');
Spy4js is primarily an ESM-first library since v3.0.0, although CJS bundles may exist. For TypeScript and modern environments, use the `import` statement. Since v3.0.0, `Spy` is a callable object, not a class, so omit the `new` keyword.
Spy.on
import { Spy } from 'spy4js'; const spy = Spy.on(someObject, 'methodName');
const spy = new Spy.on(someObject, 'methodName');
Static methods like `Spy.on` are called directly on the `Spy` export. Ensure `Spy` is imported as a named export.
Spy.mock
import { Spy } from 'spy4js'; const moduleMocks = Spy.mock(await import('./my-module'), 'useMe');
const moduleMocks = Spy.mock(require('./my-module'), 'useMe');
When mocking module exports, use `await import()` for ES Modules and `require()` for CommonJS contexts. `Spy.mock` is a static method and not a constructor.

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!');
Debug
Known issues
breakingStarting from v3.0.0, the main `Spy` export is no longer a class and cannot be instantiated with the `new` keyword. It is now a callable object.
fix
Remove the `new` keyword when creating a spy instance. Change `new Spy()` to `Spy()`.
affects: >=3.0.0
breakingAs of v3.1.0, calling `spy.hasCallHistory()` without any arguments will always fail. This method now requires arguments to check for specific call history.
fix
To check if a spy was not called at all, use `spy.wasNotCalled()`. If you need to check for specific call arguments, provide them to `spy.hasCallHistory(...)`.
affects: >=3.1.0
gotchaThe `spy4js` library explicitly states that it is not strictly necessary as most modern test frameworks (like Jest and Vitest) already include their own spying capabilities.
fix
Evaluate `spy4js` based on its specific benefits (readability, detailed error messages, unique features) rather than as a fundamental dependency for spying. It's intended as an alternative or complementary tool.
affects: *
gotchaVersion 3.1.0 introduced an 'enforce-order mode' which can be enabled via `Spy.configure({ enforceOrder: true })`. Enabling this significantly changes how spy calls are matched and validated, requiring calls to happen in a specific sequence.
fix
Be aware of this configuration option when debugging test failures related to call order. If enabling it, ensure your tests explicitly account for the exact sequence of expected calls.
affects: >=3.1.0
Errors
Common errors & fixes
TypeError: Spy is not a constructor
Attempting to create a spy instance using `new Spy()` after upgrading to spy4js v3.0.0 or higher.
fix
Remove the `new` keyword. Instantiate the spy by calling `Spy()` directly, e.g., `const mySpy = Spy();`.
Error: spy.hasCallHistory() must be called with arguments or use wasNotCalled()
Invoking `spy.hasCallHistory()` without any arguments, which is deprecated and causes an error since spy4js v3.1.0.
fix
If you intend to check if the spy was never called, use `spy.wasNotCalled()`. If you want to check for specific call patterns, provide arguments to `spy.hasCallHistory(...)`.
ERR_REQUIRE_ESM (or similar module resolution error)
Attempting to use `require()` for module mocking with `Spy.mock` in an ES Module context, or vice-versa.
fix
Ensure that your module mocking strategy aligns with your project's module system. For ES Modules (e.g., in Vitest), use `await import()` with `vi.mock()`. For CommonJS (e.g., in Jest without ESM enabled), use `require()`.
Upgrade
Version history
5.0.0latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
2 hits · last 30 days
node
2
Resources
spy4js — npm install spy4js · libregistry