Skip to content

Call the original when arguments do not match ​

Use passthrough: 'unmatched' to stub one argument value without replacing the whole method.

ts
import { createSpyFromInstance } from 'vitest-auto-spy';

const prices = createSpyFromInstance({ price: (sku: string) => sku.length }, { passthrough: 'unmatched' });
prices.price.calledWith('sale').mockReturnValue(0);

prices.price('sale'); // 0 on every matching call
prices.price('apple'); // 5 from the original

With passthrough: true, configuring calledWith still turns off the original for that method. Use 'unmatched' if you want both answers.

A class instance ​

Pass a real instance of your class. Its prototype methods are spied too, and the original runs with the instance as this.

ts
import { createSpyFromInstance } from 'vitest-auto-spy';

class PriceService {
  price(sku: string): number {
    return sku.length;
  }
}

const prices = createSpyFromInstance(new PriceService(), { passthrough: 'unmatched' });
prices.price.calledWith('sale').mockReturnValue(0);

prices.price('sale'); // 0
prices.price('apple'); // 5 from PriceService.price

createSpyFromClass has no passthrough option. It builds a double without an instance, so there is no original to call. Create the instance yourself and pass it to createSpyFromInstance.

Runner mocks and modules ​

A runner mock is a mock from your test runner, such as vi.fn(). adoptMock adopts it: it adds this library's helpers, such as calledWith, to that mock. Pass passthrough on the first adoptMock call.

For a module, pass passthrough to moduleNamespace when you build the namespace. A later adoptMock on one of its functions needs no options.

ts
import { vi } from 'vitest';
import { adoptMock, moduleNamespace } from 'vitest-auto-spy';

const mock = adoptMock(
  vi.fn((sku: string) => sku.length),
  { passthrough: 'unmatched' },
);
mock.calledWith('sale').mockReturnValue(0);

const namespace = moduleNamespace({ price: (sku: string) => sku.length }, { passthrough: 'unmatched' });
adoptMock(namespace.price).calledWith('sale').mockReturnValue(0); // the namespace already has passthrough

Which answer wins ​

For each call, the spy picks the first answer that applies:

  1. A matched calledWith answer, even undefined.
  2. On a mustBeCalledWith miss, an error. The original does not run.
  3. On a calledWith miss, an explicit default. Set it with returns, next to passthrough and keyed by method name: { passthrough: 'unmatched', returns: { price: 10 } }. Only createSpyFromInstance takes returns; moduleNamespace and adoptMock do not.
  4. Otherwise, the original. It runs once for that call.

A limited rule such as calledWith('sale').once() stops matching after its last use. Later calls with 'sale' fall through to the next step.

Instance methods run on the original instance. Module functions and adopted mocks receive the caller’s this. If the adopted mock had no implementation, a miss returns undefined.

Released under the MIT License.