npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@embedunit/spy

v0.5.0

Published

Spy and mock utilities for embedded JavaScript testing

Readme

@embedunit/spy

Spy and mock utilities for embedded JavaScript testing. Part of the embedunit monorepo.

Installation

npm install @embedunit/spy

Basic Usage

spyOn - Spy on Object Methods

import { spyOn, restoreAllSpies } from '@embedunit/spy';

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

// Create a spy on the method
const spy = spyOn(api, 'fetchData');

// By default, calls through to original
api.fetchData(); // 'real data'

// Mock the return value
spy.returnValue('mock data');
api.fetchData(); // 'mock data'

// Restore original method
spy.restore();

createSpyFunction - Standalone Spy

import { createSpyFunction } from '@embedunit/spy';

const callback = createSpyFunction('myCallback');
callback.returnValue('mocked');

someFunction(callback);

console.log(callback.callCount); // 1
console.log(callback.calls[0].args); // ['expected', 'args']

Spy Control Methods

const spy = spyOn(obj, 'method');

// Call through to original implementation (default)
spy.callThrough();

// Return a fixed value
spy.returnValue('fixed');

// Return values in sequence
spy.returnValues('first', 'second', 'third');

// Throw an error
spy.throwError(new Error('fail'));

// Use a fake implementation
spy.callFake((arg) => `faked: ${arg}`);

Call Tracking

const spy = spyOn(obj, 'method');
obj.method('a', 'b');
obj.method('c');

// Call count
spy.callCount;      // 2
spy.called;         // true
spy.notCalled;      // false
spy.calledOnce;     // false
spy.calledTwice;    // true

// Check specific calls
spy.calledWith('a', 'b');      // true
spy.neverCalledWith('x');      // true

// Access call details
spy.firstCall();   // { args: ['a', 'b'], returnValue, thisArg, timestamp }
spy.lastCall();    // { args: ['c'], ... }
spy.getCall(0);    // { args: ['a', 'b'], ... }
spy.calls;         // Array of all SpyCall objects

Async Spies

For mocking async functions and sequential returns:

import { createAsyncSpy, spyOnAsync } from '@embedunit/spy';

// Create standalone async spy
const asyncSpy = createAsyncSpy('fetchUser');

// Resolve with value
asyncSpy.resolvedValue({ id: 1, name: 'John' });
await asyncSpy(); // { id: 1, name: 'John' }

// Reject with error
asyncSpy.rejectedValue(new Error('Not found'));
await asyncSpy(); // throws Error('Not found')

// Sequential resolved values
asyncSpy.resolvedValueOnce('first');
asyncSpy.resolvedValueOnce('second');
await asyncSpy(); // 'first'
await asyncSpy(); // 'second'

// Spy on async method
const api = { fetch: async () => 'data' };
const spy = spyOnAsync(api, 'fetch');
spy.resolvedValue('mocked');

Async Spy Methods

// One-time return values
spy.returnValueOnce('once');
spy.returnValuesOnce('a', 'b', 'c');

// Async resolved/rejected
spy.resolvedValue(value);
spy.resolvedValueOnce(value);
spy.resolvedValues(v1, v2, v3);
spy.rejectedValue(error);
spy.rejectedValueOnce(error);
spy.rejectedValues(e1, e2);

// One-time fake
spy.callFakeOnce((arg) => `fake: ${arg}`);

// Clear methods
spy.clearCalls();        // Clear call history
spy.clearReturnValues(); // Clear queued returns
spy.clearAll();          // Clear everything

Mock Functions

For argument-based stubbing:

import { mock } from '@embedunit/spy';

// Create mock function
const fn = mock.mockFn<(x: number) => string>('myMock');

// Set return value
fn.mockReturnValue('default');

// Custom implementation
fn.mockImplementation((x) => `value: ${x}`);

// Argument-based stubbing
mock.when(fn(1)).thenReturn('one');
mock.when(fn(2)).thenReturn('two');
fn(1); // 'one'
fn(2); // 'two'

// Verify calls
mock.verify(fn).wasCalledWith(1);

// Reset
mock.reset(fn);

Cleanup

import { restoreAllSpies } from '@embedunit/spy';

// Restore all active spies at once
afterEach(() => {
  restoreAllSpies();
});

// Or restore individually
const spy = spyOn(obj, 'method');
spy.restore();

// Reset call history without restoring
spy.reset();

Integration with @embedunit/assert

When imported, @embedunit/spy automatically registers with @embedunit/assert to enable spy assertions:

import { expect } from '@embedunit/assert';
import '@embedunit/spy'; // Enables spy matchers

const spy = spyOn(obj, 'method');
obj.method('arg');

expect(spy).toHaveBeenCalled();
expect(spy).toHaveBeenCalledTimes(1);
expect(spy).toHaveBeenCalledWith('arg');

API Reference

Exports

  • spyOn(object, method) - Create spy on object method
  • createSpyFunction(name?, originalFn?) - Create standalone spy
  • spyOnAsync(object, method) - Create async spy on method
  • createAsyncSpy(name?, originalFn?) - Create standalone async spy
  • enhanceSpy(spy) - Add async capabilities to existing spy
  • mock - Mock function utilities
  • restoreAllSpies() - Restore all active spies
  • isSpy(value) - Check if value is a spy

License

MIT