This guide covers upgrading to 2.0.1 from 1.x (1.208.0 and older) and from the 2.0.0 betas (2.0.0-beta.0 to 2.0.0-beta.4). 2.0.1 is the first stable release of version 2; there was no 2.0.0 release. The guide describes the 2.x API, and the changelog lists every change.
Each section says which versions it applies to. Code marked "Before" is for the old version and is not valid 2.x code.
- Installing:
latestis now 2.x - Requirements
- Removed APIs:
Substitute.disableFor,clearSubstituteandClearType, stringmimick(instance) - Names that conflict with the library: the symbol API
- Behaviour changes: sequences, auto-substitutes, matcher calls, match order, re-configuring, what counts as a call,
new, checks,received(count), checks that fail later, matchers, argument comparison, omitted arguments,thisinmimicks(), protocol members, freezing andin, messages, printing - Spy assertions of jest and sinon-chai (also for tests that move from
jest.fn()or sinon spies to substitutes) - Imports and packaging
- TypeScript
The examples use this interface:
import { Substitute, Arg } from '@fluffy-spoon/substitute'
interface Calculator {
add(a: number, b: number): number
subtract(a: number, b: number): number
isEnabled: boolean
}
const calculator = Substitute.for<Calculator>()Applies to: everyone.
Up to 2.0.1, the npm latest tag pointed at 1.208.0, and the betas were published under beta. From 2.0.1 on, latest is version 2, so a plain npm install @fluffy-spoon/substitute (or a "latest" / "*" version range) now installs 2.x with the breaking changes below. A ^1 range in package.json (like ^1.208.0) keeps you on 1.x. To stay on version 1 explicitly:
npm install @fluffy-spoon/substitute@1 --save-devPrereleases are still published under the beta tag.
Applies to: everyone.
- Node.js 10 or newer for CommonJS (
require). - For the native ES module entry point (
import): Node.js 12.17 or newer on 12.x, 13.7 or newer on 13.x, or 14 or newer. On 13.2 to 13.6,importgets the CommonJS entry and named imports fail; userequirethere. - TypeScript 3.6 or newer. The 1.x README said TypeScript 3.0; 2.0.0-beta.4 needed 3.8.
strictmode, includingstrictNullChecks, is supported. The 1.x README told you to turnstrictNullChecksoff; that is no longer needed.
Applies to: 1.x and the betas.
Substitute.disableFor(sub) returned a view of the substitute in which received, didNotReceive and mimick were not the library's methods. It was used to call a member of your own with one of these names, for example in a test that wants to record such a call before checking it. It is gone, because it is no longer needed:
- A member of your own called
receivedordidNotReceiveis called as usual:fake.received(1337). - The library's checks have symbols that never conflict:
fake[received](),fake[didNotReceive](). mimickis never the library's method any more (see below), so a member calledmimickis an ordinary member.
Before:
const fake = Substitute.for<Example>()
Substitute.disableFor(fake).received(1337)
fake.received().received(1337)After:
import { Substitute, received } from '@fluffy-spoon/substitute'
class Example {
received(someNumber: number) {
return someNumber
}
}
const fake = Substitute.for<Example>()
fake.received(1337) // the class' own method, like the code under test would call it
fake[received]().received(1337)
// configuring the member works, too
fake.received(1).returns(2)
console.log(fake.received(1)) // prints 2In TypeScript, fake.received() is the class' own method here, so the string check is not offered for this type at all. In JavaScript, the library decides by how the name is used; see Names that conflict with the library. If the code under test reads a member of what its own received(...) returns, configure that call with .returns(...), so it returns your value instead of a substitute.
Applies to: the betas.
sub.clearSubstitute(clearType?) and the ClearType export were removed. What replaces them:
| Before | After |
|---|---|
sub.clearSubstitute(ClearType.receivedCalls) or sub.clearSubstitute('receivedCalls') |
sub[clearReceivedCalls]() |
sub.clearSubstitute(ClearType.substituteValues) or sub.clearSubstitute('substituteValues') |
create a new substitute |
sub.clearSubstitute() / sub.clearSubstitute(ClearType.all) |
create a new substitute |
[clearReceivedCalls]() forgets the received calls of the substitute and its auto-substitutes, and keeps every setup. There is no way to remove setups from a substitute: create the substitute in each test (for example in a beforeEach hook) instead of clearing a shared one.
Before:
import { Substitute, ClearType } from '@fluffy-spoon/substitute'
calculator.add(1, 2)
calculator.clearSubstitute(ClearType.receivedCalls)
calculator.didNotReceive().add(1, 2)After:
import { clearReceivedCalls } from '@fluffy-spoon/substitute'
calculator.add(1, 2).returns(3)
calculator.add(1, 2)
calculator[clearReceivedCalls]()
calculator.didNotReceive().add(1, 2)
console.log(calculator.add(1, 2)) // prints 3TypeScript reports the old calls as errors. In JavaScript they fail silently: sub.clearSubstitute() and sub.clearReceivedCalls() are now ordinary member calls that clear nothing, and ClearType is undefined. Search your tests for clearSubstitute, clearReceivedCalls( and ClearType.
Applies to: 1.x and the betas.
sub.mimick(instance) was typed, but did nothing in 1.x and threw "Mimick is not implemented yet" in 2.0.0-beta.4. It is replaced by the symbol sub[mimick](instance), which works: everything that is not configured is handed to the instance, and the calls are still recorded. The string mimick is now an ordinary member.
Before:
calculator.mimick(new RealCalculator())After:
import { mimick } from '@fluffy-spoon/substitute'
class RealCalculator implements Calculator {
isEnabled = true
add(a: number, b: number) { return a + b }
subtract(a: number, b: number) { return a - b }
}
calculator[mimick](new RealCalculator())
console.log(calculator.add(2, 3)) // prints 5
calculator.received().add(2, 3)A method of the instance that returns the instance itself, as a builder or an EventEmitter's on() does, answers with the substitute, so a fluent chain stays on the substitute and every call of it is recorded. In TypeScript, [mimick]() takes a partial instance of an object type, such as client[mimick]({ baseUrl: '' }). To configure members of a mimicked substitute, use sub[configure](). See Partial mocks.
Applies to: 1.x and the betas (the symbols are new in 2.0.1).
The package exports symbols for its methods: received, didNotReceive, clearReceivedCalls, mimick, configure, returns, throws, resolves, rejects and mimicks. They always mean the library's method, so they are the way to handle members with the same names as the library's methods.
clearReceivedCalls,mimickandconfigureexist only as symbols.- In TypeScript, if a type has a member called
received,didNotReceive,returns,throws,resolves,rejectsormimicks, its substitute offers onlysub[received]()andsub[didNotReceive](). Code that used the string forms on such a type no longer compiles. .returns(),.throws(),.mimicks(),.resolves()and.rejects()are not offered on a value that has its own member with that name. Use[returns]and so on there.- In JavaScript, a string check of a member called
returns,throws,resolves,rejectsormimicksis now a setup, and passes silently. In 1.x and the betas,sub.received(1).returns(5)was a check of a member calledreturns. Nowsub.received(1)followed by.returns(...)configures a member of your own calledreceived(see Names that conflict with the library). Search your tests forreceived(...).returns(,.throws(,.resolves(,.rejects(and.mimicks(, and use the symbol:sub[received](1).returns(5). - In generic code, the type parameter's constraint decides: an unconstrained
SubstituteOf<T>offerssub.received()andsub.didNotReceive(), as in 2.0.0-beta.4, while forT extends Account, whereAccounthas a member with one of these names, only the symbols are offered.
import { received, didNotReceive, returns } from '@fluffy-spoon/substitute'
calculator.add(1, 2)[returns](3)
console.log(calculator.add(1, 2)) // prints 3
calculator[received](1).add(1, 2)
calculator[didNotReceive]().subtract(Arg.all())call, apply and bind on a substitute value now mean both the function's own method and a member of your own with that name; see What counts as a call.
Applies to: 1.x.
returns(a, b, c) returns a, b and c, and then keeps returning c. In 1.x, the calls after the sequence returned undefined. The same applies to throws, resolves, rejects and mimicks with several values.
calculator.add(1, 2).returns(3, 7, 9)
console.log(calculator.add(1, 2)) // prints 3
console.log(calculator.add(1, 2)) // prints 7
console.log(calculator.add(1, 2)) // prints 9
console.log(calculator.add(1, 2)) // prints 9If a test relied on undefined after the sequence, add it to the sequence where the type allows it (returns(3, 7, 9, undefined)).
Applies to: 1.x and the betas.
A member or call that is not configured returns an auto-substitute. (The 1.x README said such calls return undefined; they returned a proxy in every version.) What is new:
- The same member, or the same method with equal arguments, always returns the same auto-substitute, so nested setups work:
app.getCalculator().add(1, 2).returns(99). - Nested checks really check. In 1.x and the betas,
app.logger.received().info('hi')passed whatever had been called. Now it fails wheninfo('hi')was not called onapp.logger. That holds through a call with a matcher, too: such a check counts the calls of the substitutes that the received calls matching it returned, so afterapp.repo('users').save(1),app.repo(Arg.any()).didNotReceive().save(1)fails andapp.repo(Arg.any()).received(1).save(1)passes (in the betas, both passed, whatever had been called), and the check changes nothing that later calls return (see Through a call with matchers). When a matching received call was answered with a value that is not a substitute, such as the promise ofapi.load(Arg.any()).resolves(user), the calls on that value cannot be counted there, so such a check throws aSubstituteExceptionthat says to check the value directly (user.received(1).save()). Tests that passed only because of this now fail. - A nested setup through a call with matchers makes every matching call answer the same substitute, as in NSubstitute: after
io.to(Arg.any()).emit(Arg.all()).returns(true),io.to('room-a') === io.to('room-b'). A check through a concrete call, such asio.to('room-b').received(1).emit('message', Arg.any())or a knex-styledb('users').received(1).where('id', 1), now counts only the calls that came through that call: it fails with "received none" when the code under test used onlyio.to('room-a'), and when calls with other arguments got the same substitute, too, it throws aSubstituteExceptionthat says to check the call itself (io.received(1).to('room-b')), configure the concrete calls, or check through the call with matchers. This holds for a check that a helper of your tests opens and returns for its caller to complete (const sentTo = (io, room) => io.to(room).received(1)), too. A route that comes back to the same substitute, as a knex-style builder whosewhere()returns the builder (query.where(Arg.all()).returns(query)) or a cycle does, is matched step by step: after the code'sdb('users').where('id', 1).first(),db('orders').where('id', 1).received(1).first()fails with "received none" (when one expression handed the builder out to steps with different arguments,where('id', 1).where('name', 'x'), a check through them is a usage error; check the builder itself). Afterio[clearReceivedCalls](), the calls that came through hand-outs made before the clear no longer count throughio's route. When the setup returns the substitute itself (io.to(Arg.any()).returns(io), a fluentreturn this), the check narrows only when it is written on one line (of the source, also under tsx); a check broken over several lines checks the substitute itself, as before, and passes for every room. See Through a call with matchers. - Setups and calls on the substitute never leak into nested members with the same name, or the other way round.
const { Substitute } = require('@fluffy-spoon/substitute')
const app = Substitute.for()
app.logger.info('hi')
app.logger.received().info('hi')
app.logger.received().info('bye') // throws SubstituteExceptionIn TypeScript, nested auto-substitutes are not typed as substitutes; see the README for the typed alternative. A check through a call with matchers needs a cast through unknown there: (app.repo(Arg.any()) as unknown as SubstituteOf<Repo>).received(1).save(1).
Applies to: 1.x and the betas.
A call with an Arg.any(), Arg.is() or Arg.all() matcher (or their .not forms) is always a setup or a check. It is never recorded as a received call, and it never runs an existing setup. Before, calculator.add(Arg.all()).returns(10) after calculator.add(1, 3).returns(1337) ran the first setup, and failed with TypeError: ... returns is not a function. A bare calculator.add(Arg.any(), 2) statement was counted as a call.
calculator.add(1, 3).returns(1337)
calculator.add(Arg.all()).returns(10)
console.log(calculator.add(1, 3)) // prints 1337
console.log(calculator.add(5, 2)) // prints 10
calculator.subtract(Arg.any(), 2)
calculator.didNotReceive().subtract(Arg.all())This also holds for matchers inside plain objects and arrays, which are new: repository.save({ id: Arg.any(), name: 'bob' }).returns('saved') is a setup, and it matches save({ id: 1, name: 'bob' }). Before, a matcher inside an object was compared as a value, so such a call was a received call and never matched anything. Matchers inside class instances, Maps and Sets are still compared as values, and so are matchers more than 32 levels deep in an argument that has none less deep. See Matchers inside objects and arrays.
Applies to: 1.x and the betas.
The README used to say that the first matching setup wins. Now the most specific setup wins: literal arguments, then matchers, then Arg.all() alone. Among setups of the same kind, the most recent one wins, so configuring the same call again overrides it. See Match order.
calculator.add(Arg.any(), Arg.any()).returns(1)
calculator.add(Arg.is(a => a > 10), Arg.any()).returns(2)
console.log(calculator.add(20, 0)) // prints 2
console.log(calculator.add(5, 0)) // prints 1Applies to: 1.x and the betas.
A call whose literal arguments match an existing setup returns the configured value, so calculator.add(1, 2).returns(5) after calculator.add(1, 2).returns(4) fails (a number has no .returns). If the configured value is a substitute, .returns(5) is silently recorded as a call of that substitute's member returns, and nothing is configured. Use the new sub[configure]() view, in which every call is a setup:
import { configure } from '@fluffy-spoon/substitute'
calculator.add(1, 2).returns(4)
calculator[configure]().add(1, 2).returns(5)
console.log(calculator.add(1, 2)) // prints 5
calculator.add(Arg.all()).returns(10)
calculator[configure]().add(1, 3).returns(1337)
console.log(calculator.add(1, 3)) // prints 1337Applies to: 1.x and the betas.
- Reading a method without calling it is not a call. Before, merely reading a method (for example to register it as an event handler) satisfied
received().method(...). .call(),.apply()and.bind()on a method, a function substitute, the result of a call or a nested member answer what the direct call answers, the configured value or the same auto-substitute, and count as a direct call, and a mimicked function or amimicks()function gets their first argument asthis. So a wrapper that forwards withfn.apply(this, args)(retry,onceand memoize helpers,sinon.spy(fn)) gets the nested setups made on the direct call, and the calls made on what it returned are checked there: afterapi.getUser(1).name.returns('bob'),withRetry(api.getUser)(1).nameis'bob'. Before, they returned a proxy of their own (in 1.x,.bind()on a method already worked). They also count as a call of a member calledcall,applyorbind, and a setup such asclient.rpc.call('getUser', 1).returns(user)configures that member. With a string or another primitive as the first argument, as for an RPC client's ownclient.rpc.call('getUser', 1), an unconfigured invocation returns an auto-substitute of its own, not the direct call's. Seecall,applyandbind.- Every call through a stored or destructured reference, or a callback, is recorded. In the betas, each such call overwrote the previous one (1.x was not affected).
- The reads and calls that lead up to a setup or a check in the same expression, like
app.getCalculator()inapp.getCalculator().add(1, 2).returns(99), are not recorded, also whengetCalculator()is configured to return a substitute (but not when it returns the substitute it is called on, as a fluentreturn thisdoes). Before, they were received calls, soapp.didNotReceive().getCalculator()failed after that setup. A check that a helper of your tests opens and returns for its caller to complete (const loggerCheck = app => app.logger.received(1)) belongs to that expression, too: the helper's reads and calls are not recorded. Calls that the code under test made are kept, also calls through a method that the test handed to it (new UserService(api.getUser), also when the code under test invokes it with the substitute asthis, as inReflect.apply(fetch, api, [id])) and calls from a promise job (Promise.resolve(id).then(getUser)): see Which calls lead to a setup or a check for how the library tells them apart. The rules that compare lines use the lines of the source wherever Node.js has a source map for the test file (tsx,node --enable-source-maps); in minified or bundled test code without one, statements on one line of the code that runs count as one expression.
const { add } = calculator
add(1, 1)
add(2, 2)
calculator.received(2).add(Arg.all())
const handler = calculator.subtract
calculator.received().subtract(Arg.all()) // throws SubstituteExceptionApplies to: 1.x and the betas.
new on a substitute or on a member of it (new sdk.Client('https://api'), also through Reflect.construct()) is a call. It is recorded, setups written as calls answer it (sdk.Client(Arg.any()).returns(client)), and checks written as calls count it (sdk.received(1).Client('https://api')). Without a setup, or with a setup that returns a primitive, new returns the auto-substitute of that call. In 1.x, new on a substitute threw a TypeError (a proxy invariant about prototype). In the betas, it returned an object made from the library's internal function, whatever was configured, and only the read of the member was recorded. In TypeScript, setups and checks written as calls compile for constructor types and members, as in Client('https://api').returns(client) for Substitute.for<new (baseUrl: string) => ApiClient>(); see Creating a substitute.
A class can extend a substitute or a member of it (class Plugin extends sdk.Base): new Plugin() is recorded as a call new Base(), and gives an instance of Plugin with its methods. A class given to mimicks() or [mimick]() constructs it, with Plugin as new.target, and assignments in the constructor (this.ready = true) create real properties. In the betas, such an instance had Plugin's methods, but the mimicked class did not run, and the assignments were not kept: this.ready read as a proxy (in 1.x, new threw). Such instances, and other objects whose prototype chain leads to a substitute, are ordinary objects: passed to a substitute, they are recorded and compared like other objects, and JSON.stringify(), util.inspect() and the printing of jest and vitest show their own fields. See Classes that extend a substitute.
const { Substitute, Arg } = require('@fluffy-spoon/substitute')
// the code under test
const connect = sdk => new sdk.Client({ baseUrl: 'https://api' })
const sdk = Substitute.for()
const client = { name: 'client' }
sdk.Client(Arg.any()).returns(client)
console.log(connect(sdk) === client) // prints true
sdk.received(1).Client({ baseUrl: 'https://api' })Applies to: the betas.
received() and didNotReceive() never run setups or mimicked implementations, and are never recorded. In the betas, checking a property ran its setup: it threw the configured error, used up a value of a returns() sequence, ran the mimicks() function again, or left an unhandled rejection behind.
calculator.isEnabled.returns(true, false)
console.log(calculator.isEnabled) // prints true
calculator.received(1).isEnabled
console.log(calculator.isEnabled) // prints falseApplies to: 1.x and the betas.
The count must be a non-negative integer, or left out for "1 or more". Anything else throws a SubstituteException that says so. Invalid counts failed before, too, but with a different error: a plain Error in 2.0.0-beta.4, a call count mismatch in 1.x. received(0) is the same as didNotReceive().
calculator.received(0).add(1, 2)
calculator.received(1.5).add(1, 2) // throws SubstituteException: Expected count has to be a non-negative integerApplies to: 1.x and the betas.
sub.didNotReceive().member or sub.received(0).member without parentheses, on a member that was called as a method, passed silently before. Now its failure is reported later, from a microtask, because the parentheses were probably forgotten: Expected to receive 0 property reads or method calls matching add, but received 1 method call. add was called 1 time as a method; to assert calls, invoke it: sub.didNotReceive().add(...). Add the call: sub.didNotReceive().add(1, 2), or .add(Arg.all()). See Assertions that fail later, which also lists how each test runner reports such a failure.
A check that nothing follows is reported, too. next.didNotReceive(), res.received(2) or sub[didNotReceive]() as a statement checks nothing; before, it passed silently. Now it is reported later, from a microtask, as @Substitute.received(2) checked nothing: it was not followed by a call or a member. Complete the check: .... Complete it with a call or a member: next.didNotReceive()(Arg.all()) checks the calls of the function substitute next itself, res.received(2).send(Arg.all()) the calls of a member. A string-form call that is most likely a member of your own (configured, answered by a mimicked instance, or with arguments that a check cannot have) is not reported; see received and didNotReceive and Names that conflict with the library. Each such check is reported, also when the same check is made again and completed later in the same synchronous code, and a matcher that throws its TypeError for invalid use in the check's own call (listener.received(1)(Arg.any('String'))) leaves only that TypeError.
const { Substitute, Arg } = require('@fluffy-spoon/substitute')
// a middleware that should not call next()
const next = Substitute.for()
next.didNotReceive()(Arg.all()) // complete: checks the calls of next itself
next.didNotReceive() // checks nothing: reported later, from a microtaskChecks that fail later (these two, and a property-style sub.received(2).member on a member that was called as a method) are reported with the queueMicrotask that the library found when it was loaded (process.nextTick on Node.js 10), so fake timers installed later in a test do not hold them back. 2.0.0-beta.4 reported a failing property-style check on process.nextTick, and an exception thrown from process.nextTick crashes jest instead of failing the test. Now jest reports it as the failure of the running test (jest 30 on Node.js 22: as a failure of the test file). mocha ties such a failure to the test only in an async test (one that returns a promise), and then reports that test a second time, as "done() called multiple times", before the run goes on; after a synchronous test, mocha stops the run, so the tests after it do not run. ava cannot tie it to the test, and ends the worker of that test file, so its unfinished tests are not reported. Every runner fails the run, though.
Applies to: 1.x and the betas.
Arg.all()after other arguments matches the rest of the arguments, and the arguments before it must match. Before, it made the whole call match anything. Arguments afterArg.all()throw aSubstituteException.Arg.any('object')no longer matchesnull, and now matches substitutes.Arg.any('function')matches substitutes, andArg.any('array')usesArray.isArray.Arg.is()with something other than a function throws aTypeErrorright away. A predicate that throws counts as a non-match instead of crashing the code under test.- Substitutes passed as arguments are compared by identity, and are never compared or printed member by member. In the betas, a failed check overflowed the stack when substitutes referred to each other through their arguments.
- JavaScript:
Arg.any(type)andArg.any.not(type)throw aTypeErrorright away for a type name that they do not know, such as a typo ('strnig') or another case ('String'). Before,Arg.any('strnig')silently matched nothing, andArg.any.not('strnig')matched every value.'bigint'is a documented type name now (it already matchedbigintvalues). - JavaScript: a matcher function passed without calling it, as a direct argument of a setup or a check (
repo.find(Arg.any).returns(user),repo.didNotReceive().delete(Arg.any)), throws aSubstituteException:Arg.any was passed as an argument without calling it, so it would only match the function Arg.any itself. Did you mean Arg.any()?(and likewise forArg.any.not,Arg.is,Arg.is.notandArg.all). Before, such a setup never answered, and such adidNotReceive()check always passed. - An
Arg.is()predicate that returns a promise or another thenable (anasyncpredicate) throws aTypeErrorwhere it is evaluated, also inside an object or an array, and its promise is handled. Before, the promise counted as a match, whatever it resolved to. In TypeScript, such a predicate does not compile. - What an
Arg.is()predicate does to a substitute argument leaves no trace: its reads and calls are not recorded and do not use upreturns()sequences, and its assignments are not made. Before, a predicate that readuser.nameof a substituteuserrecorded that read, so a lateruser.received(1).namefailed, and took the next value of the sequence away from the code under test. In a check, nothing that a predicate does while it runs leaves a trace (anasynccallback that it calls is recorded after its firstawait; drive such callbacks withmimicks()). When a call of the code under test is compared with the setups, what the code under test does in a callback that the predicate calls (Arg.is(callback => { callback(null, rows); return true })) is recorded, as before, and so is what the predicate does to substitutes that are not among the call's arguments; but a predicate runs at every comparison, also in checks, so give the setup amimicks()function to call such a callback (see Matching specific arguments). - The asymmetric matchers of jest and vitest (
expect.any(String),expect.objectContaining({ id: 1 }), ...) and sinon's matchers (sinon.match.has('err'), ...) work as matchers in setups and checks, also inside objects and arrays. Before, they were compared as values, like any other object: adidNotReceive()check with one passed whatever was called, and a setup with one never answered.Argmatchers work inside them (expect.objectContaining({ id: Arg.any() })) and in the equality of jest and vitest (expect(order).toEqual({ id: Arg.any() }), whereArg.all()stands for one value), but not inside sinon's matchers, nor as the property matchers of snapshots (useexpect.any(String)there). See Matchers of test runners. - JavaScript:
mimicks()with something other than a function (or with nothing) throws aTypeErrorat the setup, and the message names the member. Before, the setup was accepted, and the call failed later, in the code under test (TypeError: substitutionValue is not a function; in 1.x,mockValue.apply is not a function).
Applies to: 1.x and the betas.
Literal arguments are compared with deep strict equality (util.isDeepStrictEqual), as before: own enumerable properties and prototypes. #private fields and other internal state are invisible to it, so all instances of a class that keeps its state only in #private fields are equal to each other. Use the same instance, or Arg.is(), for such classes (see How arguments are compared).
Deep strict equality runs the getters of those properties. What such a getter does to a substitute while the library compares arguments (get total() { return pricing.priceOf(sku) * qty }) is not recorded and uses up no values of a returns() sequence. In 2.0.0-beta.4, it was recorded, so a check such as pricing.didNotReceive().priceOf(Arg.any()) could fail although the code under test never called priceOf.
Setups and received calls keep the argument objects themselves and compare them as they are at the time of each call or check, as before. So an argument object that you change after using it in a setup matches calls with an object equal to its new contents (see How arguments are compared).
interface Repository {
save(user: { name: string }): string
}
const repository = Substitute.for<Repository>()
const user = { name: 'ann' }
repository.save(user).returns('saved')
user.name = 'bob'
console.log(repository.save(user)) // prints saved
console.log(repository.save({ name: 'bob' })) // prints savedApplies to: the betas. 1.x compared omitted arguments in the same way.
An argument that a call leaves out at the end counts as undefined: it matches a literal undefined and matchers that accept undefined, such as Arg.any() and Arg.any('undefined'), and f(1) and f(1, undefined) are the same call. In the betas, an omitted argument matched nothing, so f(1) and f(1, undefined) were different calls. See How arguments are compared. So:
users.find(Arg.any('undefined')).returns(...)andusers.find(Arg.any()).returns(...)now answerusers.find(), andreceived(1).find(Arg.any())counts it.didNotReceive().f(Arg.any())now fails afterf(), andreceived(count).log(Arg.any(), Arg.all())countslog()as well.- A matcher setup that accepts
undefinednow answers calls with fewer arguments, and it is more specific thanArg.all(): afteradd(Arg.any(), Arg.any()).returns('p')andadd(Arg.all()).returns('w'),add(5)returns'p'. - A literal setup after a matcher setup that already answers it needs
configurenow: aftercalculator.multiply(1, Arg.any()).returns(10),calculator.multiply(1).returns(1)throwsTypeError: calculator.multiply(...).returns is not a function, becausemultiply(1)returns 10. Writecalculator[configure]().multiply(1).returns(1), or make the literal setup first. In the same way,f(undefined).returns(a)followed byf().returns(b)configures one call twice. - Only the arguments themselves count: inside arrays and objects, deep strict equality still applies, so
[1]and[1, undefined]are different.
const { Substitute, Arg } = require('@fluffy-spoon/substitute')
const logger = Substitute.for()
logger.log('started')
logger.received(1).log('started', undefined)
logger.received(1).log('started', Arg.any())
logger.didNotReceive().log('started', Arg.any()) // throws SubstituteExceptionApplies to: 1.x and the betas.
A mimicks() function is called with the this of the call, like a method: the substitute for sub.method(...), the first argument of .call() and .apply(), and undefined for a property read. Before, it was undefined (in 2.0.0-beta.4) or the library's own proxy (in 1.x). An implementation that relied on that, or that needs a this of its own, should be an arrow function or a bound method.
Applies to: 1.x and the betas.
Symbol.iterator, Symbol.asyncIterator, Symbol.hasInstance, Symbol.isConcatSpreadable, Symbol.match, Symbol.matchAll, Symbol.replace, Symbol.search, Symbol.split, Symbol.species, Symbol.toStringTag, Symbol.unscopables, util.promisify.custom, asymmetricMatch, _isMockFunction, calledWithExactly and handleEvent read as undefined on a substitute unless they are configured, and the reads are not recorded (see Special members). Before, they returned auto-substitutes. So:
[].concat(sub)keeps the substitute as one element (it was dropped),value instanceof sub.SomeClassisfalse(it wastrue),'text'.startsWith(sub.prefix)no longer throws, andutil.promisify(sub.readFile)calls the substitute, on every supported Node.js version (the running Node.js' ownutil.promisify.customis handled too; on Node.js 10.0 to 12.16.1 and 13.0 to 13.11 it is notSymbol.for('nodejs.util.promisify.custom')).- jest and vitest no longer take a substitute for a mock function when they print it. Before, jest snapshots showed a substitute as a mock function, such as
[MockFunction method<getMockName>: ()](2.0.0-beta.4) or[MockFunction [class SubstituteJS] -> getMockName](1.x). Now they show[Function], so snapshots written before need updating. See Printing a substitute. - happy-dom calls a function substitute added with
addEventListener()itself, as Node.js and jsdom do, so the events are recorded as calls of the substitute (onClick.received(1)(Arg.any())). Before, happy-dom called its auto-substitutehandleEventinstead. Code under test that callshandleEventof a substitute itself now needs it configured or mimicked; see Substitutes are functions. - sinon-chai no longer takes a substitute for a sinon spy: its assertions throw
TypeError: [Function @Substitute.name] is not a spy or a call to a spy!for a substitute. Before,expect(next).to.have.been.called,.calledOnceand.calledWith('x')passed on a substitute that was never called. See Spy assertions of jest and sinon-chai. - jest no longer takes a substitute for an asymmetric matcher. Before,
expect(fn).toHaveBeenCalledWith(sub)andexpect(list).toContainEqual(sub)passed whatever the arguments or items were, and a failingexpect(value).toEqual(sub)threw jest's internal "Unexpected return from a matcher function" error. Now they compare the substitute by identity, so tests that passed only because of this fail. - A substitute is not iterable.
[...sub],for...of,for await...ofandPromise.all(sub)on a substitute that is not configured throw aTypeError. In the betas they treated it as empty; in 1.x they threw a differentTypeError. Configure the iterator, or mimick an array:
const { Substitute, configure, mimick } = require('@fluffy-spoon/substitute')
const items = Substitute.for()
items[configure]()[Symbol.iterator]().mimicks(() => ['a', 'b'][Symbol.iterator]())
console.log([...items]) // prints [ 'a', 'b' ]
const list = Substitute.for()
list[mimick](['a', 'b'])
console.log(list.length) // prints 2__esModule is not among these members: it reads as an auto-substitute, as before. So a substitute that stands in for a whole module, for example one that a jest.mock() factory returns, still counts as an ES module for code compiled by TypeScript or Babel. Namespace and named imports reach its members, and the default import (import mailer from './mailer') is the auto-substitute mailer.default, as with 2.0.0-beta.4. To make the default import the substitute itself, return it as the default export of a plain object: jest.mock('./mailer', () => ({ __esModule: true, default: Substitute.for() })).
A substitute is a function without the own keys of a module, in every version, so it cannot stand in for a module where a tool copies the module's own keys or wants an object: a module that a barrel re-exports (export * from './mailer'), vitest's vi.mock(), node:test's mock.module(), jest's unstable_mockModule() for native ES modules, and code compiled by esbuild. Return a plain object of the substitute's members there, with the substitute as the default export: { __esModule: true, default: mailer, send: mailer.send }. Calls through these members are calls of the substitute's members, so mailer.send('ann').returns('ok') and mailer.received(1).send('ann') work on them. See Mocking a whole module for each runner.
Applies to: 1.x and the betas.
Object.freeze(),Object.seal()andObject.preventExtensions()work on a substitute and on an auto-substitute, and it keeps working afterwards. In the betas, the reads and setups after them threw aTypeError("Cannot add property _child, object is not extensible"). In 1.x, reads, setups and checks kept working, except that readinglengthornameafterwards threw aTypeError(a proxy invariant error), as readingprototypealways did.Object.defineProperty(sub, key, descriptor)defines a real property, which reads return without recording them. Before, it threw aTypeError. On a substitute that mimicks an object, it defines the member on the instance, as an assignment writes to it, anddelete sub.keydeletes the instance's member (see Partial mocks), except for a descriptor withconfigurable: false, or withoutconfigurablefor a key that the instance does not have as its own (as on any object, the default is thenfalse): that defines a property of the substitute itself, which reports it and refuses to redefine it, as a plain object does.Object.setPrototypeOf(sub, EventEmitter.prototype), for code under test that checksinstanceof, keeps the substitute working: reads, calls, assignments, setups, checks, the symbols,String()andJSON.stringify()work as before. Onlyutil.inspect()shows it as[Function: bound substitute] EventEmitterthen, also where it is an argument in a failure message. In 2.0.0-beta.4, checks, assignments andString(sub)threw aTypeErrorafterwards, such astarget.isSpecialProperty is not a function. On a frozen, sealed or non-extensible substitute,Object.setPrototypeOf()with another prototype throws aTypeErrorthat names the substitute,@Substitute is not extensible: its prototype cannot be changed after Object.freeze(), Object.seal() or Object.preventExtensions()(2.0.0-beta.4:function anonymous(...) is not extensible), and so doesReflect.setPrototypeOf(), which returnedfalsein 2.0.0-beta.4.- A substitute has no enumerable own properties:
Object.keys(sub)is empty, andReflect.ownKeys(sub)is[ 'length', 'name' ], the non-enumerable properties that every function has (lengthis0, andnameis the member's name for a member, such as'getKey'forkeys.getKey, and''for a substitute itself), unless it mimicks an object: thenObject.keys(),Object.entries(), spread,Object.assign()andfor...insee the instance's enumerable own keys, andJSON.stringify(sub)gives whatJSON.stringify(instance)gives (see Partial mocks). In the betas,Object.keys(sub)listed internal fields such as_keyand_recorder, and in 1.x and the betas,Reflect.ownKeys(sub)listedlength,nameandprototypeof the library's internal function, with its internal name. Readingsub.nameorsub.lengthis a member read, as before.util.callbackify(sub.method)works, except for a substitute that was frozen, sealed or made non-extensible, which lists nolengthandname: wrap such a substitute in a function (util.callbackify((...args) => frozen(...args))). See Freezing, defined properties andin. key in subistruefor a key with a setup, a key of a mimicked instance and a property defined withObject.defineProperty(), andfalseotherwise. Before, it answered for the library's internal function:trueforcall,lengthand the other members of functions, andfalsefor configured members. Code under test that checks for an optional member withinnow takes the branch that the test configured.
See Freezing, defined properties and in.
Applies to: 1.x and the betas.
The wording of SubstituteException messages changed, for example "Expected to receive 2 method calls matching add(1, 2), but received 1.", followed by the calls that were received (at most 50, and no more once the listed calls take 20,000 characters; a list that leaves some out ends with › … and N more). Each value in a message is printed within bounds, as described under Printing. When the expected call and a received one that it does not match print alike because they differ deeper than two levels, as filters of an ORM often do, the message prints both deeper, up to four levels. A matcher in the expected call does not count as a difference there: it prints by its label, such as Arg.any{string} for a generated id, where the received call shows the value that it was given. Nor does an order that matching ignores: of keys, as in an object built as { ...input, id }, of the entries of a Map or Set, or of the properties of an error or a function. Differences inside Maps, Sets and among the other keys of an array (such as the total of an array of rows) are found as well. Matchers in the expected call are shown by their own label at any depth (save({ user: { profile: { name: Arg.is{name => name === 'bob'} } } })). When the expected call and a received one print alike because the code under test passed another substitute, the message numbers the substitutes (@Substitute#1, @Substitute#2, ...), also those of another copy of the package, and says so in its last line; a matcher in the expected call and such orders do not count as a difference there either. Tests that compare message texts need updating. When the kind of call is not known, messages say "property reads or method calls" instead of "property calls". A check of a member that was never used at all fails when it reads the member, so its message cannot name the expected arguments ("... matching add, but received none."); once the method has been called, the message names them. A method check of a member that was only read, never called, says so: "Expected to receive 1 property read or method call matching onDone, but received 2 property reads and no method calls.", followed by a hint that reading a method is not calling it; a member whose setups give values that cannot be called, such as config.port.returns(5432), is checked as a property instead ("Expected to receive 1 property read matching port, but received 2."), also by a check with a call whose count differs from the number of reads; with a call whose count equals the number of reads (config.received(2).port()), it fails as a method check, with a last line that says that the reads answered a value that cannot be called, and gives the check without the call. When a check fails because the member was called only further down an unconfigured fluent chain (reply.code(404).send(body) checked as reply.received(1).send(body)), the message says where it was called, and how to make each method on the way return the substitute (or, when a property is read on the way, which substitute to check). The calls of a substitute that a setup with matchers gives every matching call (io.to(Arg.any()).emit(Arg.all()).returns(true)) are shown with the call that it was returned to (@Substitute.to('room-a').emit(...)), or followed by a line that names those calls. When an expected call still prints exactly like a received one that it does not match, as for objects that hold functions or #private fields, the message ends with a note that says why they can differ: "Some calls print the same but do not match: functions and symbols match by identity, and #private fields and other internal state are not printed. Match such arguments with Arg.is(), or pass the same instance." Messages contain ANSI colours only when the output is a terminal (NO_COLOR, NODE_DISABLE_COLORS, TERM=dumb and FORCE_COLOR are honoured). In the betas, messages always contained them; 1.x messages had no colours.
SubstituteException is now exported from the package root: import { SubstituteException } from '@fluffy-spoon/substitute'.
Applies to: 1.x and the betas.
String(), template strings, util.inspect(), console.log() and JSON.stringify() of an auto-substitute give its path, such as @Substitute.someProperty or @Substitute.getUser(1), followed by its received calls and setups, if it has any. Before, they gave a label such as property<someProperty>: or method<getUser>: (1) (in 1.x, [class SubstituteJS] -> someProperty). The printout of a substitute now also lists the calls and setups of its auto-substitutes, under their paths (at most 50 calls and 50 setups of them). Errors show as [Name: message] without their stack, also inside objects and arrays, followed by their own properties and their cause ([HttpError: not found] { status: 404 }). Each value is printed within bounds: two levels deep, as util.inspect() shows it by default and as the betas printed it ({ a: { b: { c: { d: 1 } } } } prints as { a: { b: { c: [Object] } } }), with the first 20 items of arrays, Maps and Sets and the first 20 keys of objects, and at most 1,000 characters; values that fit print as util.inspect(value) prints them, so small values print as in the betas. Like util.inspect(), the printout puts a value that is longer than 80 characters, or that holds more than three levels of objects, on several lines, also where it is the configured value of a setup (findById('o1') => resolves({ followed by a line for each key). A substitute that configures or mimicks toString() or valueOf() gives their result when it is converted to a string, and a substitute that mimicks an object gives that object's JSON in JSON.stringify(); util.inspect() still shows the printout. Tests that compare such texts need updating, and so do names derived from them, such as the jit_@Substitute.__anonymousType that Angular's TestBed makes for a substitute (it was jit_property<__anonymousType>: ). See Printing a substitute.
const { Substitute } = require('@fluffy-spoon/substitute')
const app = Substitute.for()
console.log(`${app.someProperty}`) // prints @Substitute.someProperty
console.log(JSON.stringify({ user: app.getUser(1) })) // prints {"user":"@Substitute.getUser(1)"}Applies to: everyone, and to tests that move from jest.fn(), jest.spyOn() or sinon spies to substitutes.
Check the calls of a substitute with received() and didNotReceive(), never with the spy assertions of jest, sinon-chai or sinon. A substitute is neither a jest mock nor a sinon spy:
- jest takes every substitute for a Jasmine-style spy, because its
calls.allandcalls.countread as auto-substitutes, which are functions, and then reads the number of calls fromcalls.count(), which gives no number. Soexpect(next).not.toHaveBeenCalled(),.not.toHaveBeenCalledTimes(1),.not.toHaveBeenLastCalledWith(...)and.not.toHaveBeenNthCalledWith(...)pass whatevernextreceived, the forms without.notfail with messages such asReceived number of calls: [Function @Substitute.calls.count().name], andtoHaveBeenCalledWith()fails with "Unexpected return from a matcher function". This is as with 2.0.0-beta.4, and it cannot change without breaking types with a member calledcalls.jest.spyOn(sub, 'save')gives the auto-substitutesub.save, which is no spy either, andtoHaveReturned()and the other matchers for return values throwreceived value must be a mock function. - sinon-chai's assertions (
.called,.calledOnce,.calledWith(...), also with.not) throwTypeError: [Function @Substitute.name] is not a spy or a call to a spy!, becausecalledWithExactlyreads asundefinednow (see Protocol members read asundefined). With 2.0.0-beta.4,expect(next).to.have.been.called,.calledOnceand.calledWith('x')passed on a substitute that was never called, so tests that passed only because of this fail now. - vitest's spy assertions throw the same
TypeError. - sinon's own assertions (
sinon.assert.called(next),sinon.assert.calledOnce(next),sinon.assert.calledWith(next, ...),sinon.assert.notCalled(next),sinon.assert.callOrder(...)) throwRangeError: Maximum call stack size exceededfor a substitute: to find the spy, sinon followsproxyandisSinonProxy, which are auto-substitutes on a substitute, without end. The reads that it makes (proxy,proxy.isSinonProxy, ...) are recorded on the substitute. sinon.spy(sub, 'save'),sinon.stub(sub, 'load'),sinon.replace(sub, 'save', fake)and node:test'smock.method(sub, 'fetch')throw aTypeError(Attempted to wrap undefined property save as function,Cannot stub non-existent property load,The argument 'methodName' must be a method) on a substitute that mimicks nothing, also for a configured member, because such a substitute reports no property descriptor for its members. Configure the member withreturns()ormimicks()instead, or spy on a reference to it:sinon.spy(sub.save)andmock.fn(sub.fetch)call the substitute, whose setups answer and whose checks count those calls. vitest'svi.spyOn(sub, 'fetch')works for a member that has a setup; for one without, it throwsError: The property "fetch" is not defined on the function., so give the member a setup first (sub.fetch(Arg.all()).returns(undefined)), or spy on a reference,vi.fn(sub.fetch).- On a substitute that mimicks an object, a method that the instance has as its own property has a property descriptor, so
jest.spyOn(),vi.spyOn(),mock.method()andsinon.replace()work: they put their spy on the instance, behind the substitute, so setups still answer first, each call is recorded once, and their restore puts the instance's function back. That holds for node:test'smock.method()with an implementation, too: the setups answer first, the mock's implementation answers the other calls, and reads ofsub.statgive the member handle (whosemockis the mock's context), not the mock. The instance's own calls of such a member throughthisstay its own (not recorded, no setup answers them), as without the spy.jest.spyOn()returns the member's handle, not jest's mock (read the mock from the instance:jest.mocked(instance.stat)), andsinon.spy(sub, 'stat')andsinon.stub(sub, 'stat')throwTypeError: Attempted to wrap stat which is already wrapped. For a method on the prototype of a class instance,mock.method()and sinon'sreplace(),spy()andstub()on the substitute throw (Cannot replace non-existent property stat, ...): put sinon on the instance instead (sinon.spy(real, 'stat'),sinon.stub(real, 'stat'),sinon.replace(real, 'stat', fake)), where setups still answer first. In TypeScript,sinon.replace(fs as Fs, 'stat', fake)needs the cast to the plain interface. See Test runners for each tool, also on a frozen instance. Before,mock.method(),vi.spyOn(),sinon.spy()andsinon.stub()silently wrapped the instance's own function, so the setups and checks of the substitute did not see those calls, andjest.spyOn(), like any wrapper that forwards to the method that it replaced (const original = sub.m; sub.m = (...args) => original(...args), as instrumentation does), made every call overflow the stack.
| jest, sinon-chai or sinon | Check |
|---|---|
expect(next).toHaveBeenCalled(), expect(next).to.have.been.called, sinon.assert.called(next) |
next.received()(Arg.all()) |
expect(next).not.toHaveBeenCalled(), expect(next).not.to.have.been.called, sinon.assert.notCalled(next) |
next.didNotReceive()(Arg.all()) |
expect(next).toHaveBeenCalledTimes(2), expect(next).to.have.been.calledTwice, sinon.assert.calledTwice(next) |
next.received(2)(Arg.all()) |
expect(next).toHaveBeenCalledWith('a', 1), expect(next).to.have.been.calledWithExactly('a', 1), sinon.assert.calledWithExactly(next, 'a', 1) |
next.received()('a', 1) |
expect(next).to.have.been.calledWith('a'), sinon.assert.calledWith(next, 'a') (the first arguments) |
next.received()('a', Arg.all()) |
expect(next).toHaveBeenCalledWith(expect.any(Error)) |
next.received()(expect.any(Error)), or next.received()(Arg.is(error => error instanceof Error)) |
expect(repository.save).toHaveBeenCalledWith(user) |
repository.received().save(user) |
The asymmetric matchers of jest and vitest, such as expect.any(Error), and sinon's matchers work in checks and setups, too (see Matchers of test runners). In TypeScript with @jest/globals, which types them as AsymmetricMatcher, cast them for parameters of other types than unknown, any or object: expect.any(String) as never.
const { Substitute, Arg } = require('@fluffy-spoon/substitute')
const next = Substitute.for()
// the code under test
next(new Error('boom'))
// Before: expect(next).toHaveBeenCalledWith(expect.any(Error)), expect(next).to.have.been.calledWith(...)
// or sinon.assert.calledWith(next, ...). With jest or vitest, next.received(1)(expect.any(Error)) works as well.
next.received(1)(Arg.is(error => error instanceof Error && error.message === 'boom'))
// Before: expect(next).not.toHaveBeenCalled(), which passes on a substitute whatever it received
next.didNotReceive()(Arg.all()) // throws SubstituteExceptionSee Test runners. With ava, t.deepEqual() reads name, constructor and constructor.name of the substitutes that it compares, and these reads are recorded; make count checks of such members before it, or compare substitutes with t.is().
Applies to: 1.x and the betas.
The ES module default import works. Under native ES modules, import Substitute from '@fluffy-spoon/substitute' used to give the CommonJS module object, so Substitute.for was not a function. It is now the Substitute class. Named imports work as before, and ES modules and CommonJS share one copy of the library.
import Substitute, { Arg } from '@fluffy-spoon/substitute'
const calculator = Substitute.for()
calculator.add(Arg.any(), 2).returns(3)
console.log(calculator.add(1, 2)) // prints 3Bundles with CommonJS output that keep the package external are an exception: they require() the CommonJS entry, so their default import is the exports object, and Substitute.for is not a function. This applies to Rollup with output.format: 'cjs' and to the SSR builds of Vite 5 to 7 with CommonJS output, for any source, and to esbuild, webpack, Rolldown and Vite 8 with CommonJS output, for .mjs sources and sources in a "type": "module" package. Use the named import import { Substitute, Arg } from '@fluffy-spoon/substitute' there, which works everywhere. With Rollup, and Vite 5 to 7, output.interop: 'auto' also makes the default import work. The second exception is ts-node's ESM loader (node --loader ts-node/esm) with module and moduleResolution set to node16 or nodenext: it type-checks the default import against the CommonJS typings and rejects Substitute.for(), so use the named import, tsx, or ts-node's transpileOnly there. See Importing.
Bundled CommonJS require() with the package external. 2.0.0-beta.4 and older had only a CommonJS entry. Now there is also an ES module entry, whose default export is the Substitute class. CommonJS code that require()s the package, bundled with Rollup's @rollup/plugin-commonjs while the package stays external (Vite 7 and older do this in SSR builds, which keep dependencies external by default), now gets that class from require(), so Substitute, Arg and the other named exports are undefined. Nothing throws at that point; the first use fails, for example with TypeError: Cannot read properties of undefined (reading 'for'). Set commonjs({ esmExternals: true }) or commonjs({ esmExternals: ['@fluffy-spoon/substitute'] }), or bundle the package (in Vite: ssr: { noExternal: ['@fluffy-spoon/substitute'] }). Vite 8 and newer, and code that imports the package, are not affected by this. See Importing.
Deep imports moved. package.json now has an exports map. The public entry point is the package root; import everything from there. 1.x had its files under dist/src/, the betas directly under dist/:
| Before | After |
|---|---|
@fluffy-spoon/substitute/dist/src/Substitute (1.x), .../dist/Substitute (betas): Substitute, SubstituteOf |
@fluffy-spoon/substitute |
@fluffy-spoon/substitute/dist/src/Arguments (1.x), .../dist/Arguments (betas): Arg |
@fluffy-spoon/substitute |
@fluffy-spoon/substitute/dist/src/SubstituteBase (1.x), .../dist/SubstituteException (betas): SubstituteException |
import { SubstituteException } from '@fluffy-spoon/substitute' |
@fluffy-spoon/substitute/dist/src/Transformations (1.x), .../dist/Transformations (betas): ObjectSubstitute, ... |
SubstituteOf<T> from @fluffy-spoon/substitute |
import { SubstituteOf, SubstituteException } from '@fluffy-spoon/substitute'
const asSubstitute: SubstituteOf<Calculator> = calculator
try {
asSubstitute.received().add(1, 2)
} catch (error) {
console.log(error instanceof SubstituteException) // prints true
}The other files were internals and are gone without a replacement: in 1.x dist/src/Context, dist/src/Utilities and dist/src/states/...; in the betas dist/SubstituteNode, dist/SubstituteNodeBase, dist/Recorder, dist/RecordsSet, dist/RecordedArguments, dist/Types and dist/Utilities (dist/utilities/... in 2.0.0-beta.4). Development builds made from the repository after 2.0.0-beta.4 had them under dist/internals/ (dist/internals/SubstituteNode, dist/internals/Recorder, dist/internals/RecordsSet, ...); those are gone, too.
The compiled files of 2.0.1 live under dist/api, dist/internals and dist/shared. They are not public API and can change in any release. They can be imported as @fluffy-spoon/substitute/dist/<path>, with or without .js, on Node.js 14.19 or newer on 14.x, 16.9 or newer on 16.x, any later version, and versions older than 12.17 (which ignore exports). On 12.17 to 12.19, 13.x and 14.0 to 14.12, deep imports fail; on 12.20 to 12.22, 14.13 to 14.18 and 16.0 to 16.8, only the form without .js works. @fluffy-spoon/substitute/dist/api, .../dist/api/types and .../dist/shared, the directories that the published declarations import, resolve to their index on every Node.js version from 10.0 on. Other directories (dist/internals, dist/internals/utilities) do not resolve on Node.js versions that read exports.
require works on every Node.js version from 10 on, and import needs 12.17 or newer on 12.x, 13.7 or newer on 13.x, or 14 or newer (see Requirements).
Applies to: 1.x and the betas.
The typings were reworked. Most code compiles unchanged, but:
- The symbol rules above: string checks are not offered on types with conflicting member names, and
mimick(instance)is symbol only. - The symbol API is available on every substitute, also on
SubstituteOf<T>for a genericT. In generic code, the string formssub.received()andsub.didNotReceive()are offered for a type parameter without a constraint, as in the betas. With a constraint, the constraint decides: if it has a member calledreceived,didNotReceive,returns,throws,resolves,rejectsormimicks, only the symbols are offered. Calls and properties that return the type parameter keep.returns()and the other setup methods. - With a constrained type parameter (
function stub<T extends Calculator>(sub: SubstituteOf<T>), or a fixture classFixture<T extends Calculator>withsub = Substitute.for<T>()), setups, checks and theconfigureview work through the constraint:sub.total.returns(1),sub.add(1, 2).returns(3),sub.received().total = 1andsub[configure]().add(1, 2).returns(3)compile, and the values are checked against the constraint's member types. With 2.0.0-beta.4, only property setups and checks of calls compiled there. Keys that exist only through the constraint's string index signature (T extends { [key: string]: number; port: number },sub.timeout.returns(5)) can be configured, too, with values of the index signature's type. The exceptions (see Typing limitations):- On older TypeScript versions only: on 3.6 to 4.7, calls of optional methods (and of members typed
fn | undefined) have no setup API in such code; on 3.6 to 3.8, members whose type includesnullorundefinedhave none either, and neither domaybe?: TororNull: T | nullof any type parameter, constrained or not, in an interface such asBox<T>. Configure them throughsub[configure](), which works on every version. - A union constraint whose variants' methods return different types (
T extends Cat | Dog, withspeak(): 'meow'andspeak(): 'woof'):.returns()takesneverthere. Cast to the constraint:(pet as SubstituteOf<Cat | Dog>).speak().returns('meow'). - On TypeScript 5.4 and newer, a method that the variants of a union constraint declare with different parameter lists (
T extends LogA | LogB, withlog(message: string): voidandlog(message: string, level?: number): void) has no setup API, even when every variant returns the same type. Use theconfigureview (sub[configure]().log('x').returns()) or cast to the constraint. Checks work. - A set of a key that exists only through the index signature cannot be checked (
sub.received().timeout = 5). Write(sub.received() as Settings).timeout = 5. - A promise-typed property of the constraint (
name: Promise<string>withT extends Repo) has no.resolves()or.rejects()(string form, symbol form orconfigureview), while promise-returning methods have them. Writerepo.name.returns(Promise.resolve(value)), or.returns(Promise.reject(error)), which work on every supported version. Concrete types are not affected.
- On older TypeScript versions only: on 3.6 to 4.7, calls of optional methods (and of members typed
- A member whose type is a union of function types with different return types (
onResult: ((r: string) => number) | ((r: string) => string)), and a method whose return type differs between the variants of a union (Substitute.for<Cat | Dog>()withload(): Promise<number>andload(): Promise<string>, or methods that returnthis), have the setup API with the union of the return types:listeners.onResult('a').returns(1)and.returns('x'),pet.load().resolves(1)and.resolves('x'),.mimicks()and theconfigureview. With 2.0.0-beta.4,.resolves()on such methods, and.returns()on methods that returnthisand on union-typed callback members, tooknever, and calls of a substitute of a union of function types (Substitute.for<((e: string) => number) | ((e: string) => string)>()) had no setup API. - The same holds for a method that the variants of a union declare with different parameter lists (an extra optional parameter, other parameter types, other overloads):
client.fetch('/a').resolves('ok')forfetch(url)andfetch(url, options?)inSubstitute.for<ClientV1 | ClientV2>(), andreader.read('p').returns('text')and.returns(new Uint8Array())forread(path): stringandread(path, encoding?): Uint8Array..returns()takes the return types of the variants that the call can reach, which depends on the number of arguments that the call passes. Each call is checked against one variant's parameter list as a whole, so arguments that no variant accepts together (move('a', 'b')formove(x: string, y: number)andmove(x: number, y: string)) do not compile, and a callback without parameter types gets them from that list. A callback that annotatesthiswith the type of a variant (function (this: Button, x: number) { }) compiles and takes that variant's return type; with 2.0.0-beta.4, such calls did not compile. Typing limitations has the exact rule, and the cases that need a cast to one variant (such asArg.any()where the variants' parameter types differ). With 2.0.0-beta.4,.returns()on such methods was missing or tookneverwhen the return types differ, and on TypeScript 5.4 and newer it was missing even when they are the same. Unions whose variants have a string index signature ({ kind: 'a'; [key: string]: unknown; speak(): 'meow' } | ...) take the union of the return types as well; with 2.0.0-beta.4,.returns()was missing there. - Substitutes of constructor types and members that are classes support the setups and checks written as calls that
newneeds:Client('https://api').returns(client)andClient.received(1)('https://api')forSubstitute.for<new (baseUrl: string) => ApiClient>(), andsdk.Client(Arg.any()).returns(client)andsdk.received(1).Client('https://api')for a memberClient: typeof ApiClient.new Client('https://api')keeps the constructor's parameter and instance types. A constructor type with several construct signatures has the call syntax for each of them. .resolves()and.rejects()configure a native promise, and are offered on every member that a native promise of the value fits:Promise<T>and its subtypes without members of their own (such as Prisma'sPrismaPromise<T>, which only narrows[Symbol.toStringTag]),PromiseLike<T>, and unions such asvoid | Promise<void>orstring | Promise<string>. With 2.0.0-beta.4, they were offered only when the return type is a promise. They are not offered for a thenable with members of its own, such as a query builder (interface Query extends PromiseLike<Row[]> { where(...): Query }), nor for a subtype ofPromisewith members of its own, such as ky'sResponsePromise(json(),text()), knex'sQueryBuilder(where()), execa's result (kill()) or aCancellablePromisewithcancel(): a native promise has no such members. 2.0.0-beta.4 offered them for suchPromisesubtypes, and the code under test then failed with "... is not a function" when it called one of those members. Configure such a member with.returns(): a substitute of the type for code under test that calls its members, or a native promise with the members added (Object.assign(Promise.resolve(1), { cancel: () => { } })) for code under test that awaits it. See Working with promises..returns()and.resolves()(also[returns](),[resolves]()and theconfigureview) can be called without a value wheneverundefinedis a valid value: forany,unknown,void,undefinedandT | undefined, as in Koa'snext().resolves()orrepo.findById('42').resolves()forPromise<User | undefined>. With 2.0.0-beta.4, only avoidvalue could be left out.- Generic methods (
get<K extends keyof Config>(key: K): Config[K]) have the setup API with their type parameters replaced by their constraints, and the configured value is checked against what the method returns for them, also for arguments that fit only the constraints (same(1, 'x')forsame<T extends string | number>(a: T, b: T): Ttakesstring | number). On Node.js'EventEmitter<Events>,Arg.all()after the leading arguments ofemit()(orders.received(1).emit('paid', Arg.all())) compiles, with the leading arguments checked againstemit()'s own signature, with@types/node18.19.63 to 24.x; from@types/node25 on,emit()takes any event and any arguments on a substitute, and an untypedArg.is()predicate getsanythere. AnArg.is()predicate in the arguments of a typed emitter'semit()needs a parameter type (Arg.is((orderId: string) => ...)), and a type parameter's default is not used, so pino'slogger.child(...)takes aLogger<string>in.returns(). A call with too many or too few arguments is rejected, except for Node.js'EventEmitter<Events>.emit, and, on TypeScript 3.6 to 3.9, for generic methods whose rest parameter is typed by an indexed access (send<K extends keyof Events>(event: K, ...args: Events[K])), which take any number of arguments on a substitute there. A method whose return type is conditional on a type parameter (convert<T>(value: T): T extends string ? number : boolean) has the setup API, too, and.returns()takes any value there; with 2.0.0-beta.4, it took only the type of one branch (boolean). See Typing limitations. Arg.any('bigint')is typedbigint.sub[mimick](instance)takes a partial instance of an object type (client[mimick]({ baseUrl: '' })for aClientwith other members, too), with members of the type's member types only. Function types, arrays, tuples and primitives take a whole instance, and in generic code the instance is aT(also for a substitute ofT | undefinedorT | null). In an object literal,thisis the partial type, so a fluent method casts it:res[mimick]({ status() { return this as Response } }). 2.0.0-beta.4 had only the stringmimick(instance), which took a whole instance (see the stringmimick(instance)).Arg.any('string')is typedstring, as with 2.0.0-beta.4 (andArg.any('number')number, and so on), so overloads such as Node.js'on(event: 'close', ...)next toon(event: string, ...), or lib.dom'squerySelector(), take the overload for any string. It does not fit a parameter typed with a union of string literals ('EUR' | 'USD'), a string enum, a branded string (string & { __brand: 'OrderId' }), a union of number literals (80 | 443) or the encoding of Node.js'fs.readFile(). WriteArg.is((currency: Currency) => true)orArg.any('string') as Currencythere (as unknown as OrderIdfor a branded type). See Matching by type.- Overloaded generic methods whose parameter types depend on a type parameter through a conditional type, such as
@types/pg'sPool.queryandClientBase.query, have no setup API for a call that passes values (pool.query(sql, [1]).resolves(result)), as with 2.0.0-beta.4. Pass the valuesas never(pool.query(sql, [1] as never).resolves(result), the same call at runtime), or match the SQL with any values (pool.query(sql, Arg.all())). See Typing limitations. - On an overloaded method whose overloads return different types, a setup with
Arg.all()alone takes any overload's value, sopool.query(Arg.all()).resolves(result)compiles with@types/pg, and.mimicks()takes a function that fits each overload, as a function assigned to the method does: it may leave out trailing parameters ((entity: any) => ...,entity => ...,async path => ...,(text: string) => ...for@types/pg'squery(text, values?)andquery(text, callback)), and its untyped parameters get the parameter types of all the overloads at their position. Make parameters that some overload does not pass optional ((key?: string) => ...forget()next toget(key)), or take(...args: any[]). A union of functions (cond ? takesEveryCall : takesOneRow) fits only when each of them does. With 2.0.0-beta.4, it took the value of the first overload (a stream forpool.query()). On overloads whose return types depend on their type parameters, such as TypeORM'sRepository.save(), an untyped parameter of amimicks()function is typed with the constraints (DeepPartial<User>[] | DeepPartial<User>), so a function that returns its argument needs a type:users.save(Arg.all()).mimicks(async (entity: any) => entity)or.mimicks(entity => Promise.resolve(entity as any)), not.mimicks(async entity => entity). On such overloads, a setup withArg.any()for an argument whose type is the type parameter itself has no setup API (users.save(Arg.any()).resolves(user), TS2339), as with 2.0.0-beta.4: useArg.all(), a typedArg.is((saved: User) => ...),Arg.any() as Useror a value. Where the argument's type only contains the type parameters, as in AWS SDK v3'ss3.send(command), it is the other way round understrict:Arg.any(),Arg.all()and an untyped predicate that narrows (Arg.is(command => command instanceof GetObjectCommand)) have the setup API, while a concrete command, a typed predicate and a cast get the client's own overload (TS2339), becauseCommandis invariant in its type parameters. Checks take every form. See Typing limitations. When all the overloads return the same type, as fastify'saddHookoverloads do,.mimicks()takes the parameters of the first overload (of the last 8, which count). See Ignoring all arguments. - A method or callable member whose last overload no argument fits once its type parameters are replaced by their constraints, such as hono 4's
Context.getandContext.setwith an emptyContextVariableMap, has the setup API now:c.get('user').returns(user),c[configure]().get('user').returns(user)andc.get(Arg.all()).returns(user)compile (with 2.0.0-beta.4, onlyc.get(Arg.any())did). The overloads that remain are typed as other generic methods, so.returns()takes the value of any variable, and a value read from the substitute itself (const user: User = c.get('user')) does not compile: read it through theContexttype. Only such a last overload that returnsneveronce its type parameters are replaced is left out; Typing limitations has the exact rule for other impossible overloads. - A check through a call with matchers (
app.repo(Arg.any()).received(1).save(1)) needs a cast throughunknown, because the result of a call is typed as the member's value with the setup API, without the check views:(app.repo(Arg.any()) as unknown as SubstituteOf<Repo>).received(1).save(1). See Through a call with matchers. - An
Arg.is()predicate can return any value that is not a promise (Arg.is(user => user.name),Arg.is(user => user.name?.startsWith('a'))); with 2.0.0-beta.4, it had to return aboolean. - A member called
thenis typednever: substitutes are never thenables. - Members typed only
nullorundefined(error?: undefined,ownerDocument: null) keep their plain type and no longer have.returns()and the other setup methods. Configure them throughsub[configure](). In a union, a member that is onlynullorundefinedin some variants ({ data: string[]; error: null } | { data: null; error: Error }, or{ ok: true; value: string; error?: undefined } | { ok: false; value?: undefined; error: Error }) has the setup API with the type the variants have in common (result.data.returns(null)). With 1.x and the betas, the: nullform turned the substitute intonever(on TypeScript 3.9 and newer); the?: undefinedform compiled with 2.0.0-beta.4. - Substitutes of function types and of interfaces with call signatures are typed:
Substitute.for<(event: string) => string>()supportslistener('saved').returns('ack'),listener.received(1)('saved'),listener[received](1)('saved')andlistener[configure]()('saved').returns('ack'). With 2.0.0-beta.4, the setup and the checks of such calls did not compile. Arg.any('function')is typed as any function or class, so it fits typed callback parameters.Arg.any('object')is typedany, likeArg.any()(it wasobject).Arg.any('undefined')only fits parameters and properties that acceptundefined, such as an optional parameter,number | undefinedorunknown. It was typednever, which fit every parameter, so code likecalculator.add(Arg.any('undefined'), 2)no longer compiles.Arg.any.not('undefined')fits any parameter.- Now supported: optional members (also
sub.received().optionalProperty = undefined, for optional properties that are not functions), named members next to an index signature, overloads without parameters, up to 8 overloads,(...args: unknown[])methods,.throws()on methods that returnnever,Arg.all()after other arguments (after up to 6 of them), and types with very large unions of string literals, such as lib.dom'sHTMLInputElement. - An optional function-typed property (
onChange?: (value: string) => void) does not acceptundefinedin a check. Write(widget.received() as Widget).onChange = undefined, orwidget.received().onChange = Arg.any.not('function'). - In a project compiled with
declaration: true(orcomposite: true), a file can export a substitute, a check view (export const view = pet.received()) or a function that returns one, but no longer the value of a member or a call of a substitute (export const sum = calc.add(1, 2)) or theconfigureview: TypeScript reports TS4023 ("has or is using name 'returns' ... but cannot be named"), because the setup methods are keyed by the library's symbols now. Give such a value the member's type (export const sum: number = calc.add(1, 2)), or export a function that sets up and returns the substitute. 2.0.0-beta.4 emitted declarations for them. Check views of types with members keyed by symbols (iterables,Map, Node.js'EventEmitterand streams) can be exported, too. The type of a check view is exported asCheckViewOf<T>, so a generic helper that returns one, in the string or the symbol form, is annotated asfunction once<T>(sub: SubstituteOf<T>): CheckViewOf<T> { return sub[received](1) }, also withisolatedDeclarations(ReturnType<SubstituteOf<T>['received']>does not compile in generic code). A generic helper whose inferred type is a substitute ofT | undefinedorT | null, or a member or check view of a substitute of a constrained type parameter, needs a type annotation (function optional<T>(sub: SubstituteOf<T | undefined>): SubstituteOf<T | undefined>,CheckViewOf<T>for a check view, and the constraint's types for a member of a constrained one): without one, TypeScript 3.6 does not finish, 4.5 runs out of memory, and 4.1, 4.9, 5.0 and 5.2 report TS7056 ("The inferred type of this node exceeds the maximum length the compiler will serialize"), and so do 5.4 and newer for the members and check views of a constrained type parameter. The declaration of a member of a check view or of an exported matcher, emitted withmoduleResolution: nodeby TypeScript 5.9 and older, refers to the directory@fluffy-spoon/substitute/dist/shared, which the package'sexportsmap to its index, sonode16,nodenextandbundlerprojects read it with full types. See Typing limitations. - See Typing limitations for what TypeScript cannot express.