diff --git a/CHANGELOG.md b/CHANGELOG.md index e9f583b..611fcf0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,20 +3,20 @@ All notable changes to `@fluffy-spoon/substitute` are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). Upgrading? Read the [migration guide](MIGRATION.md). -## [2.0.1] - Unreleased +## [2.0.1] - 2026-11-23 The first stable release of version 2 (there was no 2.0.0 release). It is published as the npm `latest` version, which was 1.208.0 until now. See the [migration guide](MIGRATION.md) for upgrading from 1.x or from a beta. ### Added - Symbols for the library's methods, exported from the package root: `received`, `didNotReceive`, `clearReceivedCalls`, `mimick`, `configure`, `returns`, `throws`, `resolves`, `rejects` and `mimicks`. They always mean the library's method, so they handle members with the same names, and they work when two copies of the package are installed. - `sub[configure]()`: a view of a substitute in which every call and property read is a setup. Use it to change a call that is already configured, or to configure a mimicked substitute. A setup through a member or call that answers with a substitute goes to that substitute; through one that answers with a real value, it throws a `SubstituteException`. -- `sub[mimick](instance)`: hands everything that is not configured to a real instance. Calls are still recorded, and setups still win. A method or getter of the instance that returns the instance itself (a fluent `return this`, as in builders, `EventEmitter.on()` or `stream.setEncoding()`) answers with the substitute, so a chain stays on the substitute and each of its calls is recorded. A method read from the substitute is a handle that calls the instance's function as it was when it was read, as on an ordinary object, so wrapping a member and forwarding to it (`const original = client.query; client.query = function (...args) { return original.apply(this, args) }`, as instrumentation libraries, retry decorators and spies do) runs the original once and records the call once, and the spies of jest, vitest, node:test and sinon (`sinon.replace()`; `sinon.spy()` and `sinon.stub()` throw) put their wrapper on the instance, behind the substitute, so setups still answer first, also with an implementation of node:test's `mock.method()`, and the instance's own calls of such a member through `this` stay its own, as without the spy (see the README, "Partial mocks" and "Test runners", also for methods on a class prototype, where sinon goes on the instance itself, and for frozen instances). In TypeScript, it takes a partial instance of an object type (`client[mimick]({ baseUrl: '' })`), and in generic code a `T`, also for a substitute of `T | undefined` or `T | null`. +- `sub[mimick](instance)`: hands everything that is not configured to a real instance. Calls are still recorded, and setups still win. A method or getter of the instance that returns the instance itself (a fluent `return this`, as in builders, `EventEmitter.on()` or `stream.setEncoding()`) answers with the substitute, so a chain stays on the substitute and each of its calls is recorded. A method read from the substitute is a handle that calls the instance's function as it was when it was read, as on an ordinary object, so wrapping a member and forwarding to it (`const original = client.query; client.query = function (...args) { return original.apply(this, args) }`, as instrumentation libraries, retry decorators and spies do) runs the original once and records the call once, and the spies of jest, vitest, node:test and sinon (`sinon.replace()`; `sinon.spy()` and `sinon.stub()` throw) put their wrapper on the instance, behind the substitute, so setups still answer first, also with an implementation of node:test's `mock.method()`, and the instance's own calls of such a member through `this` stay its own, as without the spy (see the guide, "Partial mocks" and "Test runners", also for methods on a class prototype, where sinon goes on the instance itself, and for frozen instances). In TypeScript, it takes a partial instance of an object type (`client[mimick]({ baseUrl: '' })`), and in generic code a `T`, also for a substitute of `T | undefined` or `T | null`. - `sub[clearReceivedCalls]()`: forgets the received calls of a substitute and its auto-substitutes, and keeps the setups. - `SubstituteException` is exported from the package root, for `instanceof` checks. - TypeScript: the type `CheckViewOf`, what `received()`, `didNotReceive()`, `[received]()` and `[didNotReceive]()` return, is exported from the package root, so a generic helper that returns a check view can be annotated, in the string and the symbol forms, also under `isolatedDeclarations`: `function once(sub: SubstituteOf): CheckViewOf { return sub[received](1) }`. Declaration files that TypeScript 4.5 and newer emit for a check view refer to it as `import("@fluffy-spoon/substitute").CheckViewOf<...>`. - Auto-substitutes are cached, so nested setups and checks work at runtime: `app.getCalculator().add(1, 2).returns(99)` and `app.logger.received().info('hi')`. - `Arg.all()` after other arguments matches the rest of the arguments, including none: `log('x', Arg.all())`. In TypeScript, this type-checks after up to 6 other arguments. - Matchers inside plain objects and arrays, also nested ones: `repository.save({ id: Arg.any(), name: 'bob' }).returns('saved')`. `Arg.all()` as the last item of an array matches the remaining items. They are found in arrays and objects of any size, up to 32 levels deep, and at any depth in an argument that has one less deep. -- A native ES module entry point and an `exports` map, with typings for the `node16`, `nodenext` and `bundler` module resolutions. The ES module entry point shares one copy of the library with CommonJS. It is checked on every change with Node.js, Rollup with `@rollup/plugin-commonjs`, webpack, esbuild, a Vite SSR build with `ssr.noExternal` and vitest with `server.deps.inline` (also with `deps.interopDefault: false`). Bundles with CommonJS output that keep the package external load the CommonJS entry, so their default import is the exports object, and ts-node's ESM loader type-checks the default import against the CommonJS typings; use the named import `import { Substitute, Arg } from '@fluffy-spoon/substitute'` there (see the README, "Importing"). +- A native ES module entry point and an `exports` map, with typings for the `node16`, `nodenext` and `bundler` module resolutions. The ES module entry point shares one copy of the library with CommonJS. It is checked on every change with Node.js, Rollup with `@rollup/plugin-commonjs`, webpack, esbuild, a Vite SSR build with `ssr.noExternal` and vitest with `server.deps.inline` (also with `deps.interopDefault: false`). Bundles with CommonJS output that keep the package external load the CommonJS entry, so their default import is the exports object, and ts-node's ESM loader type-checks the default import against the CommonJS typings; use the named import `import { Substitute, Arg } from '@fluffy-spoon/substitute'` there (see the guide, "Importing"). - `console.log`, `util.inspect`, `String()` and `JSON.stringify()` show a substitute's setups and received calls, also those of its auto-substitutes (at most 50 calls and 50 setups of them), under their paths. An auto-substitute shows its path, such as `@Substitute.logger` or `@Substitute.getUser(1)`, and its own setups and calls. Printing always ends, also for substitutes stored in the arguments of their own calls, and for chains of any length (long paths are shortened in the middle). Each value is printed within bounds, so that a large argument, such as a DOM event that refers to its window or an object with thousands of keys, takes a few lines: two levels deep, as `util.inspect()` shows values by default (`{ a: { b: { c: { d: 1 } } } }` prints as `{ a: { b: { c: [Object] } } }`), with the first 20 items of arrays, `Map`s and `Set`s and the first 20 keys of objects, and at most 1,000 characters (values that fit print as `util.inspect(value)` prints them). Matchers inside objects and arrays are shown by their own label at any depth. Errors, in printouts and failure messages, 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 }`. - `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')`). In TypeScript, these setups and checks compile for constructor types (for each of their construct signatures) and for members that are classes. A class can extend a substitute or a member of it (`class Plugin extends sdk.Base`): `new` gives an instance of the subclass, constructed by a mimicked class with the subclass as `new.target`, and the class has the `call`, `apply` and `bind` of every function, so `new (Plugin.bind(null, 'audit'))()` constructs it. Such instances 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. What Node.js reads through them while the library compares or prints them (`href`, `protocol`, `auth`) is not recorded on the substitute, also when another copy of the package does the comparing or printing: the copies share a marker for that on the global object, under `Symbol.for('@fluffy-spoon/substitute:guard')`. - `Arg.any('bigint')`. @@ -32,11 +32,12 @@ The first stable release of version 2 (there was no 2.0.0 release). It is publis - A [migration guide](MIGRATION.md), this changelog and [contributing guidelines](CONTRIBUTING.md). The README examples are type-checked and run in CI, and the oldest supported TypeScript version is checked there, too. ### Changed +- The README is now a short overview with a quick start and a cheat sheet. The full reference moved to [docs/GUIDE.md](docs/GUIDE.md), where every example is still type-checked and run on every change. - When several setups match a call, the most specific one wins: literal arguments, then matchers, then `Arg.all()` alone. Among setups of the same kind, the most recent one wins, and configuring the same call again replaces it. (The README said that the first matching setup wins.) - A call with an argument matcher (`Arg.any`, `Arg.is`, `Arg.all`, also with `.not`, also inside an object or array) is always a setup or a check. It is never recorded as a received call and never runs an existing setup. - The reads and calls that lead up to a setup or a check in the same expression, like `app.getCalculator()` in `app.getCalculator().add(1, 2).returns(99)`, are not recorded as received calls. Calls that the code under test made are kept, also when the test then configures or checks the value they returned. That includes calls through a method that the test handed to the code under test (`new UserService(api.getUser)`), which are made, and shown in failure messages, where the code under test invokes them, also with the substitute as `this` (`Reflect.apply(fetch, api, [id])`), and calls from a promise job (`Promise.resolve(id).then(getUser)`). A member configured to return another substitute counts like an auto-substitute here: after `app.getCalculator().returns(calculator)`, `app.getCalculator().add(1, 2).returns(3)` records no `getCalculator()` call. A check that a helper opens and returns for its caller to complete (`const sentTo = (io, room) => io.to(room).received(1)`) belongs to the expression that opens it, wherever it is completed. - Reading a method without calling it is no longer a call; method checks count invocations only. -- `.call()`, `.apply()` and `.bind()` on a substitute value also count as a call of a member called `call`, `apply` or `bind`, and a setup written through them configures that member. Failure messages and `String(sub)` show such a call once, as in `rpc(1) via .call('getUser', 1)`. A nested setup or a check through an unconfigured `call` or `apply` whose first argument is `undefined`, `null`, an object or a function, as in a wrapper's `fn.apply(this, args)`, goes to the auto-substitute of the direct call. With a primitive first argument, as in an RPC client's own `client.rpc.call('getUser', 1)` or ioredis' `redis.call('get', key)`, the invocation has an auto-substitute of its own for its arguments as they are, so `client.rpc.call('getUser', 1)` and `client.rpc.call('deleteUser', 1)` stay apart. An API whose own `call` takes an object first, such as web3's `method.call({ from })`, shares the auto-substitute of `method()` for every object unless a call is configured (see the README, "`call`, `apply` and `bind`"). +- `.call()`, `.apply()` and `.bind()` on a substitute value also count as a call of a member called `call`, `apply` or `bind`, and a setup written through them configures that member. Failure messages and `String(sub)` show such a call once, as in `rpc(1) via .call('getUser', 1)`. A nested setup or a check through an unconfigured `call` or `apply` whose first argument is `undefined`, `null`, an object or a function, as in a wrapper's `fn.apply(this, args)`, goes to the auto-substitute of the direct call. With a primitive first argument, as in an RPC client's own `client.rpc.call('getUser', 1)` or ioredis' `redis.call('get', key)`, the invocation has an auto-substitute of its own for its arguments as they are, so `client.rpc.call('getUser', 1)` and `client.rpc.call('deleteUser', 1)` stay apart. An API whose own `call` takes an object first, such as web3's `method.call({ from })`, shares the auto-substitute of `method()` for every object unless a call is configured (see the guide, "`call`, `apply` and `bind`"). - A `mimicks()` function and a mimicked function get the `this` of the call: the substitute for `sub.method(...)`, and the first argument of `.call()` and `.apply()`. - **JavaScript:** `sub.received(count)` or `sub.didNotReceive()` followed by `.returns()`, `.throws()`, `.resolves()`, `.rejects()` or `.mimicks()` configures a member of your own called `received` or `didNotReceive`. In 2.0.0-beta.4 and 1.x it was a check of a member called `returns` (and so on), so such checks now pass silently. Use the symbols: `sub[received](1).returns(5)`. - **JavaScript:** `sub.received(count)` or `sub.didNotReceive()` followed directly by a call, like `listener.received(1)('saved')`, checks a call of the substitute itself. @@ -49,11 +50,11 @@ The first stable release of version 2 (there was no 2.0.0 release). It is publis - A substitute no longer exposes internal fields: `Object.keys(sub)` is empty, unless the substitute mimicks an object (see above), and `Reflect.ownKeys(sub)` gives the non-enumerable `length` and `name` that every function has (`length` is `0`, `name` is the member's name for a member, such as `'getKey'`, and `''` otherwise), so `util.callbackify(sub.method)` and wrappers that copy a function's name work (2.0.0-beta.4 listed `length`, `name` and `prototype` of the library's internal function, with its internal name). - `key in sub` is `true` for a key with a setup, a key of a mimicked instance and a property defined with `Object.defineProperty()`, and `false` otherwise (calls and checks through a call with a matcher do not count as setups); it records nothing. In 2.0.0-beta.4 it answered for the library's internal function (`true` for `call` and `length`, `false` for configured members). - Failure messages say what kind of call was expected: method calls, property reads, property assignments, or "property reads or method calls" when that is not known. They show the path of nested substitutes, also for a substitute passed as an argument (`@Substitute`, `@Substitute.child`), of the same or of another copy of the package (2.0.0-beta.4 printed it in full, with its calls), show a call made with `new` as `new Client(...)`, and list at most 50 received calls, and no more once the listed calls take 20,000 characters. When the checked member was never used at all, the message cannot name the expected arguments; once the method has been called, it does. A method check of a member that was only read, never called, fails with a hint that reading is not calling, whatever the expected count (for `didNotReceive()`, also how to reset the reads); its message says "property reads or method calls" when the count differs from the number of reads. A member whose setups give values that cannot be called (`returns()` of a value that is neither a function nor a substitute, `resolves()`, `rejects()`, `throws()`, or a mimicked instance's value that is not a function) is checked as a property instead: "Expected to receive 1 property read matching port, but received 2.", without a hint, also by a check with a call whose count differs from the number of reads; a check with a call whose count equals the number of reads, or with no count (`config.received(2).port()`), fails as a method check, and its last line says that the reads answered a value that cannot be called, and gives the check without the call (`sub.received(2).port`). When a check fails because the member was called only further down an unconfigured chain, as the second call of `reply.code(404).send(body)` or `span.setAttribute(key, value).setStatus(status)` is, the message names up to three such places and says to make each method on the way return the substitute (`sub.code(Arg.all()).returns(sub) and sub.header(Arg.all()).returns(sub)` for `reply.code(404).header(name, value).send(body)`) or to mimick an instance whose methods return `this`, or, when a property is read on the way, which substitute to check, by its whole path (`sub.users.where({ id: 1 }).limit(1).received(1).exec(...)`), written as code that can be run (`sub['my-key']`, `sub[Symbol.for('k')]`, the concrete call that a shared substitute was returned to) when every argument on the way prints as code that gives an equal value, or else named as messages print it, to be reached with the same arguments (a `Date`, a class instance, a function or a matcher on the way), or not given when it cannot be written. The calls of a substitute that a setup with matchers gives every call that it matches are shown with the call that it was returned to (`@Substitute.to('room-a').emit(...)`), and when it was returned to calls with different arguments, a line under the list of calls names them. Messages contain ANSI colours only when the output is a terminal, and honour `NO_COLOR`, `FORCE_COLOR`, `NODE_DISABLE_COLORS` and `TERM=dumb`. -- Failed checks throw right away. Only a check that nothing follows (see above), and a property-style check (`sub.received(2).member` or `sub.didNotReceive().member`, not followed by a call) on a member that was called as a method, are reported later, from a microtask (see the README). Such a report uses the `queueMicrotask` that the library found when it was loaded (`process.nextTick` on Node.js 10). 2.0.0-beta.4 used `process.nextTick`, from which jest cannot attribute an exception to a test; jest now reports the failure of the running test (jest 30 on Node.js 22: of the test file). mocha ties such a failure to the test only in an `async` test, which it then reports a second time ("done() called multiple times") before it goes on, or, when the test's promise settles after the last test, throws that second error after the summary and exits with code 7; after a synchronous test, it stops the run. ava cannot tie it to a test, and ends the worker of that test file (see the README, "Assertions that fail later"). A matcher that throws its `TypeError` for invalid use cancels such a report only when it belongs to the same check (called on the same line as the member is read, in the same function). +- Failed checks throw right away. Only a check that nothing follows (see above), and a property-style check (`sub.received(2).member` or `sub.didNotReceive().member`, not followed by a call) on a member that was called as a method, are reported later, from a microtask (see the README). Such a report uses the `queueMicrotask` that the library found when it was loaded (`process.nextTick` on Node.js 10). 2.0.0-beta.4 used `process.nextTick`, from which jest cannot attribute an exception to a test; jest now reports the failure of the running test (jest 30 on Node.js 22: of the test file). mocha ties such a failure to the test only in an `async` test, which it then reports a second time ("done() called multiple times") before it goes on, or, when the test's promise settles after the last test, throws that second error after the summary and exits with code 7; after a synchronous test, it stops the run. ava cannot tie it to a test, and ends the worker of that test file (see the guide, "Assertions that fail later"). A matcher that throws its `TypeError` for invalid use cancels such a report only when it belongs to the same check (called on the same line as the member is read, in the same function). - TypeScript: on a type with a member called `received`, `didNotReceive`, `returns`, `throws`, `resolves`, `rejects` or `mimicks`, only the symbol forms `sub[received]()` and `sub[didNotReceive]()` are offered. In generic code, the type parameter's constraint decides; an unconstrained `SubstituteOf` offers the string forms. `.returns()` and the other setup methods are offered unless the configured value has its own member with that name. -- TypeScript: `.resolves()` and `.rejects()` are no longer offered for subtypes of `Promise` with members of their own, such as ky's `ResponsePromise`, knex's `QueryBuilder`, execa's result or a `CancellablePromise` with `cancel()`. 2.0.0-beta.4 offered them, and the code under test then failed with "... is not a function" when it called one of those members on the native promise. Configure such members with `.returns()` (see the README, "Working with promises"). Subtypes without members of their own, such as Prisma's `PrismaPromise`, keep them. +- TypeScript: `.resolves()` and `.rejects()` are no longer offered for subtypes of `Promise` with members of their own, such as ky's `ResponsePromise`, knex's `QueryBuilder`, execa's result or a `CancellablePromise` with `cancel()`. 2.0.0-beta.4 offered them, and the code under test then failed with "... is not a function" when it called one of those members on the native promise. Configure such members with `.returns()` (see the guide, "Working with promises"). Subtypes without members of their own, such as Prisma's `PrismaPromise`, keep them. - TypeScript: a member called `then` is typed `never`, because substitutes are never thenables. -- TypeScript: with `declaration: true` (or `composite: true`), a file can export a substitute, a check view (`export const view = pet.received()`, also of a union substitute) and a function that returns one, but not the value of a member or a call of a substitute (`export const sum = calc.add(1, 2)`) or the `configure` view, which fail with TS4023 ("has or is using name 'returns' ... but cannot be named") because their setup methods are keyed by the library's symbols; 2.0.0-beta.4 emitted declarations for them. 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 (see the README, "Typing limitations"). Check views of types with members keyed by symbols (iterables, `Map`, `Set`, Node.js' `EventEmitter`, streams and servers) can be exported as well. Generic helpers whose inferred type is a substitute of `T | undefined` or `T | null`, or a member or check view of a substitute of a constrained type parameter, need a type annotation: 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 (see the README for the annotations that work, such as `CheckViewOf` for a check view). The declaration files that TypeScript 5.9 or older emits with `moduleResolution: node` for a member of a check view or an exported matcher refer to the directory `@fluffy-spoon/substitute/dist/shared`; the `exports` map sends it, and `dist/api` and `dist/api/types`, to their index, so `node16`, `nodenext` and `bundler` projects read them with full types. +- TypeScript: with `declaration: true` (or `composite: true`), a file can export a substitute, a check view (`export const view = pet.received()`, also of a union substitute) and a function that returns one, but not the value of a member or a call of a substitute (`export const sum = calc.add(1, 2)`) or the `configure` view, which fail with TS4023 ("has or is using name 'returns' ... but cannot be named") because their setup methods are keyed by the library's symbols; 2.0.0-beta.4 emitted declarations for them. 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 (see the guide, "Typing limitations"). Check views of types with members keyed by symbols (iterables, `Map`, `Set`, Node.js' `EventEmitter`, streams and servers) can be exported as well. Generic helpers whose inferred type is a substitute of `T | undefined` or `T | null`, or a member or check view of a substitute of a constrained type parameter, need a type annotation: 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 (see the README for the annotations that work, such as `CheckViewOf` for a check view). The declaration files that TypeScript 5.9 or older emits with `moduleResolution: node` for a member of a check view or an exported matcher refer to the directory `@fluffy-spoon/substitute/dist/shared`; the `exports` map sends it, and `dist/api` and `dist/api/types`, to their index, so `node16`, `nodenext` and `bundler` projects read them with full types. - TypeScript: members typed only `null` or `undefined` keep their plain type and have no setup API (configure them through `sub[configure]()`). - TypeScript: `Arg.any('function')` is typed as any function or class, so it fits typed callback parameters. `Arg.any('object')` is typed `any`. - TypeScript: `Arg.any('undefined')` only fits parameters and properties that accept `undefined`. It was typed `never`, which fit every parameter (`calculator.add(Arg.any('undefined'), 2)` compiled). `Arg.any.not('undefined')` fits any parameter. @@ -62,7 +63,7 @@ The first stable release of version 2 (there was no 2.0.0 release). It is publis - Releases are published to npm with provenance: stable versions as `latest`, prereleases as `beta`. - The internal caches, the hashing of arguments and the search and printing budgets that the development builds after 2.0.0-beta.4 added to make large tests faster are removed again, to keep the code simple. So tests with very large arguments or very many calls run slower than with those builds. Arguments that hold matchers inside objects or arrays that many other objects share, many levels deep, are the slowest: for a dependency graph of 12 levels of three packages that share one `deps` array, with a matcher in each package, a failure message takes about 25 seconds to build, and a printout of the substitute about 13 seconds (matching such arguments took seconds in every version). - An error among the other keys of an array of more than 1,000 items prints without its stack, as everywhere else (`... 981 more items, failure: [TypeError: bad]`); the development builds after 2.0.0-beta.4 printed its stack there. -- Source maps decide the lines of CommonJS test files on Node.js 12.17 to 14.17, too (see the README, "Which calls lead to a setup or a check"); the development builds after 2.0.0-beta.4 did not find them there. +- Source maps decide the lines of CommonJS test files on Node.js 12.17 to 14.17, too (see the guide, "Which calls lead to a setup or a check"); the development builds after 2.0.0-beta.4 did not find them there. - A check through a concrete call on a substitute that a setup with matchers shares (`io.to('room-b').received(1).emit(...)`) counts only the calls that came through that call, or throws a `SubstituteException` when they cannot be told apart, however many steps the check has; the development builds after 2.0.0-beta.4 stopped looking after 1,000 steps and then counted the calls that came through the other calls, too. ### Fixed @@ -76,8 +77,8 @@ The first stable release of version 2 (there was no 2.0.0 release). It is publis - `Arg.all()` after other arguments ignored those arguments. - A failed check overflowed the stack when substitutes referred to each other through their arguments, and threw a `TypeError` with `Error.stackTraceLimit = 0`. The library also works with a read-only, getter-only, frozen (`Object.freeze(Error)`) or deleted `Error.stackTraceLimit`, and leaves the property as it is (in the development builds after 2.0.0-beta.4, the first three made every operation throw a `TypeError`). Where V8 collects no stack frames (a limit that is 0, missing, not a number or an accessor), the library captures none either; with a frozen `Error` it cannot read them. Then position alone decides which calls lead to a setup or a check (see the README). - An exception thrown by an `Arg.is()` predicate escaped into the code under test. -- An `Arg.is()` predicate, or a matcher of a test runner, that reads or calls members of a substitute argument recorded these reads and calls on it and used up the values of its `returns()` sequences, in checks and when the calls of the code under test were compared with setups. Now what a matcher does to a substitute argument while it looks at it leaves no trace, and in a check, nothing that it does while it runs leaves one (an `async` callback that it calls is recorded after its first `await`). When a call of the code under test is compared with the setups, what the code under test does in a callback that a predicate calls, and what a predicate does to substitutes that are not among the call's arguments, are recorded as before; use `mimicks()` to call such callbacks (see the README, "Matching specific arguments"). -- A getter of an argument that reads or calls a substitute (`get total() { return pricing.priceOf(sku) * qty }`) recorded these reads and calls, and used up the values of `returns()` sequences, when the library compared the argument with a setup. Now what such a getter does while the library compares arguments, for a call, a setup or a check, leaves no trace (see the README, "How arguments are compared"). +- An `Arg.is()` predicate, or a matcher of a test runner, that reads or calls members of a substitute argument recorded these reads and calls on it and used up the values of its `returns()` sequences, in checks and when the calls of the code under test were compared with setups. Now what a matcher does to a substitute argument while it looks at it leaves no trace, and in a check, nothing that it does while it runs leaves one (an `async` callback that it calls is recorded after its first `await`). When a call of the code under test is compared with the setups, what the code under test does in a callback that a predicate calls, and what a predicate does to substitutes that are not among the call's arguments, are recorded as before; use `mimicks()` to call such callbacks (see the guide, "Matching specific arguments"). +- A getter of an argument that reads or calls a substitute (`get total() { return pricing.priceOf(sku) * qty }`) recorded these reads and calls, and used up the values of `returns()` sequences, when the library compared the argument with a setup. Now what such a getter does while the library compares arguments, for a call, a setup or a check, leaves no trace (see the guide, "How arguments are compared"). - With an `Error.prepareStackTrace` that writes no `Error` line above the frames, the `called at` lines of failure messages named the frame below the call (such as `Module._compile`). They now name the call, and a report that comes later names the line of the check. - A revoked proxy among the arguments, such as an immer draft after `produce()` has finished, made every call, setup and check with it throw `TypeError: Cannot perform 'getPrototypeOf' on a proxy that has been revoked`. It now matches by identity, also next to a matcher, and prints as `` where Node.js' `util.inspect()` can print one (not on Node.js 16.9 and older). So does a proxy whose keys cannot be listed (its `ownKeys` or `getOwnPropertyDescriptor` trap throws). A revoked proxy of a function is a value like any other as well, also as the value of a setup, of a member or of a mimicked instance, and a check through a call with matchers whose matching call returned a revoked proxy is the `SubstituteException` for values that are not substitutes, which names it ``. - `Object.setPrototypeOf(sub, prototype)` broke a substitute: later checks, assignments and `String(sub)` threw a `TypeError`. Now everything but `util.inspect()`'s printout keeps working, and `instanceof` sees the new prototype. @@ -90,11 +91,11 @@ The first stable release of version 2 (there was no 2.0.0 release). It is publis - TypeScript: a substitute of a function type or of an interface with call signatures had no setup or check API for its own calls. `listener('saved').returns('ack')`, `listener.received(1)('saved')`, `listener[received](1)('saved')` and `listener[configure]()('saved').returns('ack')` now compile. - TypeScript: in generic code over a constrained type parameter (`(sub: SubstituteOf)`, or `Substitute.for()` in a fixture class), call setups (`sub.add(1, 2).returns(3)`) and property checks (`sub.received().total = 1`) did not compile. Setups, checks and the new `configure` view now work through the constraint, also for keys that exist only through the constraint's string index signature (with exceptions, most of them on TypeScript older than 4.8; see the README, "Typing limitations"). - TypeScript: on a member whose type is a union of function types with different return types (`onResult: ((r: string) => number) | ((r: string) => string)`), and on methods of a union whose return types differ and that return a promise or `this` (`Substitute.for()`), `.returns()` or `.resolves()` took `never`, and calls of a substitute of a union of function types had no setup API. They now take the union of the variants' return types: `pet.load().resolves(1)` and `pet.load().resolves('x')` for `Promise | Promise`. -- TypeScript: on a method that the variants of a union declare with different parameter lists (an extra optional parameter, other parameter types, other overloads), such as `read(path): string` and `read(path, encoding?): Uint8Array` in `Substitute.for()`, `.returns()` was missing or took `never` when the return types differ, and on TypeScript 5.4 and newer it was missing even when they are the same (`fetch(url)` and `fetch(url, options?)`, both returning `Promise`). Such methods now have the setup API, which takes the return types of the variants that the call can reach, depending on the number of arguments it passes (see the README, "Typing limitations", for the exact rule). Each call is checked against one variant's parameter list as a whole, so arguments that no variant accepts together do not compile, and a callback without parameter types gets them from that list. A callback that annotates `this` with the type of a variant whose method takes it compiles, too, also followed by `Arg.all()`. -- TypeScript: setups of the generic methods of Node.js' `EventEmitter` did not compile (`orders.emit('paid', 'o1', 20).returns(true)`: "This expression is not callable"; `orders.on('paid', listener).returns(orders)`), nor did `Arg.all()` after the event in a check of a typed `emit()` (`emitter.received(1).emit('saved', Arg.all())`). Generic methods now have the setup API, the checks and the `configure` view, with their type parameters replaced by their constraints (see the README, "Typing limitations", for what that cannot check). With `@types/node` 18.19.63 to 24.x, `emit()`'s leading arguments are checked against its own signature; from `@types/node` 25 on, a substitute takes any event and arguments there. +- TypeScript: on a method that the variants of a union declare with different parameter lists (an extra optional parameter, other parameter types, other overloads), such as `read(path): string` and `read(path, encoding?): Uint8Array` in `Substitute.for()`, `.returns()` was missing or took `never` when the return types differ, and on TypeScript 5.4 and newer it was missing even when they are the same (`fetch(url)` and `fetch(url, options?)`, both returning `Promise`). Such methods now have the setup API, which takes the return types of the variants that the call can reach, depending on the number of arguments it passes (see the guide, "Typing limitations", for the exact rule). Each call is checked against one variant's parameter list as a whole, so arguments that no variant accepts together do not compile, and a callback without parameter types gets them from that list. A callback that annotates `this` with the type of a variant whose method takes it compiles, too, also followed by `Arg.all()`. +- TypeScript: setups of the generic methods of Node.js' `EventEmitter` did not compile (`orders.emit('paid', 'o1', 20).returns(true)`: "This expression is not callable"; `orders.on('paid', listener).returns(orders)`), nor did `Arg.all()` after the event in a check of a typed `emit()` (`emitter.received(1).emit('saved', Arg.all())`). Generic methods now have the setup API, the checks and the `configure` view, with their type parameters replaced by their constraints (see the guide, "Typing limitations", for what that cannot check). With `@types/node` 18.19.63 to 24.x, `emit()`'s leading arguments are checked against its own signature; from `@types/node` 25 on, a substitute takes any event and arguments there. - TypeScript: in a property check on a substitute of a union (`Substitute.for()`), a matcher could not be assigned to a member that is a function (`pet.received().speak = Arg.any('function')`). Functions and constructors (`String`, `Date`, classes) are still rejected there, as TypeScript rejects them for the union itself. - TypeScript: an `Arg.is()` predicate had to return a `boolean`, so `Arg.is(user => user.name)` and `Arg.is(user => user.name?.startsWith('a'))` did not compile, although any truthy value matches. It can now return any value that is not a promise; an `async` predicate still does not compile. -- TypeScript: a setup with `Arg.all()` alone on an overloaded method took the value of the first overload, so `pool.query(Arg.all()).resolves(result)` did not compile with `@types/pg` (whose first overload returns a stream). On an overloaded method whose overloads return different types, `Arg.all()` alone now takes any overload's value, and `.mimicks()` a function that fits each overload, as a function assigned to the method does: it may leave out trailing parameters (`(entity: any) => ...`, `async path => ...`, `(text: string) => ...` for `@types/pg`'s `query(text, values?)` and `query(text, callback)`), and an untyped parameter gets the parameter types of all the overloads at its position, on every supported TypeScript version. A parameter that does not take what some overload passes is rejected (`(key: string) => key` for `get(): string[]` and `get(key: string): string`; make it optional), and a union of functions fits only when each of them does. On overloads whose return types depend on their type parameters, such as TypeORM's `Repository.save()`, a function that returns its argument needs a type (`async (entity: any) => entity`), and a setup with `Arg.any()` for an argument whose type is the type parameter itself has no setup API (use `Arg.all()`, a typed `Arg.is()`, a cast or a value), while for one whose type only contains the type parameters, as in AWS SDK v3's `client.send(command)`, `Arg.any()`, `Arg.all()` and an untyped narrowing predicate have it and a concrete command, a typed predicate or a cast do not (see the README, "Typing limitations"). When all the overloads return the same type, as fastify's `addHook` overloads do, `.mimicks()` takes the parameters of the first overload (of the last 8, which count). +- TypeScript: a setup with `Arg.all()` alone on an overloaded method took the value of the first overload, so `pool.query(Arg.all()).resolves(result)` did not compile with `@types/pg` (whose first overload returns a stream). On an overloaded method whose overloads return different types, `Arg.all()` alone now takes any overload's value, and `.mimicks()` a function that fits each overload, as a function assigned to the method does: it may leave out trailing parameters (`(entity: any) => ...`, `async path => ...`, `(text: string) => ...` for `@types/pg`'s `query(text, values?)` and `query(text, callback)`), and an untyped parameter gets the parameter types of all the overloads at its position, on every supported TypeScript version. A parameter that does not take what some overload passes is rejected (`(key: string) => key` for `get(): string[]` and `get(key: string): string`; make it optional), and a union of functions fits only when each of them does. On overloads whose return types depend on their type parameters, such as TypeORM's `Repository.save()`, a function that returns its argument needs a type (`async (entity: any) => entity`), and a setup with `Arg.any()` for an argument whose type is the type parameter itself has no setup API (use `Arg.all()`, a typed `Arg.is()`, a cast or a value), while for one whose type only contains the type parameters, as in AWS SDK v3's `client.send(command)`, `Arg.any()`, `Arg.all()` and an untyped narrowing predicate have it and a concrete command, a typed predicate or a cast do not (see the guide, "Typing limitations"). When all the overloads return the same type, as fastify's `addHook` overloads do, `.mimicks()` takes the parameters of the first overload (of the last 8, which count). - TypeScript: 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.get` and `Context.set` (`(key: Key)` last, with an empty `ContextVariableMap`), had no setup API: `c.get('user').returns(user)` failed with TS2339, and `c.get(Arg.all())` matched no overload (TS2769). Such a last overload is now left out of the setup API, the `configure` view and the `Arg.all()` setup, when it returns `never` once its type parameters are replaced; how other impossible overloads are typed is in the README ("Typing limitations"). - TypeScript: a generic method whose return type is conditional on a type parameter (`convert(value: T): T extends string ? number : boolean`) took only the type of one branch in `.returns()`. It now takes any value there. - TypeScript: a union whose variants declare a member as only `null` or `undefined`, like `{ data: string[]; error: null } | { data: null; error: Error }`, turned the substitute into `never`.