diff --git a/.github/workflows/nodejs.yml b/.github/workflows/nodejs.yml index c95bd2af..7b1cc92f 100644 --- a/.github/workflows/nodejs.yml +++ b/.github/workflows/nodejs.yml @@ -49,7 +49,7 @@ jobs: run: npm test - name: Run the type tests run: npm run test:types --if-present - # Type-checks and runs the code examples of README.md and MIGRATION.md against the built package, and checks links. + # Type-checks and runs the code examples of README.md, docs/GUIDE.md, MIGRATION.md and CHANGELOG.md against the built package, and checks links. - name: Check the code examples in the documentation run: npm run test:docs diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d97ae5bf..cac765f7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -29,7 +29,7 @@ npm ci | `src/` | The library source (TypeScript). `src/index.ts` is the public entry point. | | `spec/` | The runtime specs, run with [ava](https://github.com/avajs/ava). | | `spec-types/` | Type-level tests of the public typings (`npm run test:types`), and `spec-types/min-ts/`, which checks the built typings with the oldest supported TypeScript (`npm run test:types:min-ts`). | -| `spec-docs/` | The documentation check (`npm run test:docs`): it type-checks and runs the code examples of the README, MIGRATION and CHANGELOG. See [spec-docs/README.md](spec-docs/README.md). | +| `spec-docs/` | The documentation check (`npm run test:docs`): it type-checks and runs the code examples of the README, the guide (docs/GUIDE.md), MIGRATION and CHANGELOG. See [spec-docs/README.md](spec-docs/README.md). | | `packaging/` | Packaging checks (run as part of `npm test`), the ES module wrapper generator and the smoke tests. | | `compatibility-checks/` | A separate npm project that checks the packed package with ava, jest, mocha, node:test and vitest, and bundles it with Rollup, webpack, esbuild and Vite. | | `dist/` | Build output that gets published (generated, not committed). | @@ -134,7 +134,7 @@ npm run test:types Type-level tests in `spec-types/` check the public typings with the TypeScript compiler of this repository (`spec-types/` with `strict`, `spec-types/loose/` without). `spec-types/declaration-emit/` is compiled with `declaration: true` and `emitDeclarationOnly`, as a project with `declaration` or `composite` would build it: it -exports check views of substitutes, which must emit without errors (the README, "Typing limitations", says what +exports check views of substitutes, which must emit without errors (the guide, "Typing limitations", says what cannot be exported). It writes the declaration files into `node_modules/.cache/substitute-spec-types-declaration-emit`, which git ignores. CI runs them with `npm run test:types --if-present`. @@ -166,7 +166,7 @@ them is missing. npm run test:docs ``` -This builds `dist/` and checks every code example in `README.md`, `MIGRATION.md` and `CHANGELOG.md`: TypeScript +This builds `dist/` and checks every code example in `README.md`, `docs/GUIDE.md`, `MIGRATION.md` and `CHANGELOG.md`: TypeScript examples are type-checked against the built package and run, JavaScript examples are run, and their `// prints ...` and `// throws ...` comments must hold. Relative links and `#anchors` must resolve. It then runs a self-test against deliberately broken fixtures. A change to the library's behaviour or typings that breaks a @@ -175,7 +175,7 @@ and the directives that mark blocks (`compile-only`, `esm`, `skip`, ...), are de [spec-docs/README.md](spec-docs/README.md). The examples are type-checked with the `@types/node` of this repository (18.19.x). An example of what only older -`@types/node` versions declare, such as the README's limitations of Node.js' `EventEmitter` with +`@types/node` versions declare, such as the the guide's limitations of Node.js' `EventEmitter` with `@types/node` up to 24, is marked `types-node-below=25`: with a newer `@types/node`, the check says that it did not check that block, instead of failing. The examples that need a test runner (jest, vitest) are marked `skip`, and the compatibility checks below run the same code. @@ -187,10 +187,10 @@ not against `src/`, and checks two things: - `test/index.ts`: every supported test runner (ava, jest, mocha, node:test, vitest, and vitest with the package inlined through `vitest.inline.config.mts`) reports a failing Substitute assertion, including one that is thrown - after the test function has returned, and checks what each runner then does with the tests around it, as README + after the test function has returned, and checks what each runner then does with the tests around it, as the guide "Assertions that fail later" describes. For mocha, it does so with a synchronous test (`test-runners/mocha/`) and with an `async` test (`test-runners/mocha-async/`), which mocha reports twice, the second time as "done() called - multiple times" (as long as the run is still going when the test's promise settles; README "Assertions that fail + multiple times" (as long as the run is still going when the test's promise settles; the guide "Assertions that fail later" describes the other case). It also runs these suites, which must pass: - `test-runners/jest-matchers/` (`npm run validate:jest-matchers`): substitutes used inside jest matchers compare by identity, so a non-matching `expect(fn).toHaveBeenCalledWith(substitute)` fails and @@ -199,29 +199,29 @@ not against `src/`, and checks two things: values that hold substitutes print paths and do not show substitutes as mock functions, and that instances of classes that extend a substitute are ordinary objects in `toEqual()`, `toHaveBeenCalledWith()`, inline snapshots, setups and checks, and that jest's asymmetric matchers (`expect.any()`, - `expect.objectContaining()`, ...) work as matchers in setups and checks, as README "Matchers of test runners" - documents. `jest.fn(substitute)` must answer what the substitute answers (README "What counts as a call"). + `expect.objectContaining()`, ...) work as matchers in setups and checks, as the guide "Matchers of test runners" + documents. `jest.fn(substitute)` must answer what the substitute answers (the guide "What counts as a call"). `spyon-mimicked.spec.ts` checks `jest.spyOn()`, node:test's `mock.method()` and an instrumentation wrapper (`const original = obj.m; obj.m = wrap(original)`) on a substitute that mimicks an instance: setups still - answer, each call is recorded once, and the restore gives the instance its function back (README "Partial + answer, each call is recorded once, and the restore gives the instance its function back (the guide "Partial mocks" and "Test runners"). `spies-mimicked-round18.spec.ts` checks node:test's `mock.method()` with an implementation (setups first, then the mock) and that the instance's own calls through `this` of a member that `jest.spyOn()`, node:test or a wrapper replaced are not recorded, and `sinon-mimicked-round18.spec.ts` pins what sinon (22, a dev dependency of the checks) does on a mimicked substitute: `sinon.replace()` for an own method, the `TypeError`s of `spy()`, `stub()` and, for a method on a class prototype, `replace()`, and sinon on the - instance itself (README "Test runners"). + instance itself (the guide "Test runners"). - `test-runners/vitest-matchers/` (`npx vitest run ./test-runners/vitest-matchers/index.spec.ts`): the same for vitest's matchers, snapshots and diffs (including the checks and setups with vitest's asymmetric matchers that the - README's vitest example makes, and `vi.fn(substitute)`), and how vitest and `util.inspect` see printed, frozen and + the guide's vitest example makes, and `vi.fn(substitute)`), and how vitest and `util.inspect` see printed, frozen and `in`-probed substitutes. - `test-runners/jest-modules/` (`npm run validate:jest-modules-ts` and `npm run validate:jest-modules-babel`): a substitute that stands in for a whole module (a `jest.mock()` factory), imported by the code under test as a namespace, with named imports, with a default and named import together, and as a default export through the - factory that README "Mocking a whole module" documents, and a module re-exported by a barrel (`export *`), mocked + factory that the guide "Mocking a whole module" documents, and a module re-exported by a barrel (`export *`), mocked either through the barrel itself or with a plain object of the substitute's members (`barrel-substitute.spec.ts`, `barrel-members.spec.ts`). It runs once compiled by ts-jest with `esModuleInterop` (`jest.modules.ts-jest.config.js`) and once by babel-jest (`jest.modules.babel.config.js`). - - Module mocks that need a plain object of a substitute's members, as README "Mocking a whole module" shows: + - Module mocks that need a plain object of a substitute's members, as the guide "Mocking a whole module" shows: vitest's `vi.mock()` (`test-runners/vitest-modules/`, `npm run validate:vitest-modules`), node:test's `mock.module()` (`test-runners/nodejs-modules/`, `npm run validate:nodejs-modules`, with `--experimental-test-module-mocks`) and jest's `unstable_mockModule()` for native ES modules @@ -230,7 +230,7 @@ not against `src/`, and checks two things: substitutes that mimick an instance and on those that do not (`spies-mimicked.test.mjs`), and that the instance's own calls through `this` of a member that `vi.spyOn()` replaced stay its own (`spies-mimicked-round18.test.mjs`). - - `test-runners/tsx-lines/`: the same checks of the line rules (README "Which calls lead to a setup or a check", + - `test-runners/tsx-lines/`: the same checks of the line rules (the guide "Which calls lead to a setup or a check", "Lines in transpiled test files") run with `node --import tsx` (`checks.ts` and `checks.mts`) and with `node --require tsx/cjs`, which put each file on one line, and must give what they give with a statement per line of the code that runs. @@ -242,7 +242,7 @@ not against `src/`, and checks two things: It also bundles `bundlers/require-entry.mjs`, which imports CommonJS code that `require()`s the package (`bundlers/require-helper.cjs`). With `@rollup/plugin-commonjs` on default options and the package kept external, that `require()` gets the `Substitute` class instead of the exports object (Vite 7 and older SSR builds do the - same, since they externalize dependencies). README "Importing" and MIGRATION "Imports and packaging" document + same, since they externalize dependencies). the guide "Importing" and MIGRATION "Imports and packaging" document this and its workarounds, and the check makes sure each of them gives the exports object: `commonjs({ esmExternals: true })`, `commonjs({ esmExternals: ['@fluffy-spoon/substitute'] })`, bundling the package, Vite's `ssr.noExternal: ['@fluffy-spoon/substitute']`, and the default externals of the Vite version @@ -253,7 +253,7 @@ not against `src/`, and checks two things: external, and a Vite SSR build with `output.format: 'cjs'`. Such a bundle `require()`s the package at run time, and its default import follows Node.js's CommonJS interop: it is the exports object, not the `Substitute` class (with Rollup for every source; with esbuild, webpack and Rolldown, which Vite 8 uses, for `.mjs` sources and - sources in a `"type": "module"` package). README "Importing" and MIGRATION "Imports and packaging" recommend the + sources in a `"type": "module"` package). the guide "Importing" and MIGRATION "Imports and packaging" recommend the named import there. The check bundles `bundlers/named-entry.mjs`, which uses only the named import, with each of them; bundles `bundlers/entry.mjs` with Rollup's `output.interop: 'auto'`, which makes the default import work; and checks that the caveat itself still holds for `bundlers/entry.mjs` with each of them. diff --git a/MIGRATION.md b/MIGRATION.md index 0ea2bf04..fae3665e 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -1,5 +1,5 @@ # Migration guide -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 [README](README.md) describes the 2.x API, and the [changelog](CHANGELOG.md) lists every change. +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](docs/GUIDE.md) describes the 2.x API, and the [changelog](CHANGELOG.md) 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. @@ -85,7 +85,7 @@ fake.received(1).returns(2) console.log(fake.received(1)) // prints 2 ``` -In 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](README.md#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. +In 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](docs/GUIDE.md#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. ### `clearSubstitute` and `ClearType` *Applies to: the betas.* @@ -155,7 +155,7 @@ 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]()`](README.md#re-configuring-a-call-configure). See [Partial mocks](README.md#partial-mocks). +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]()`](docs/GUIDE.md#re-configuring-a-call-configure). See [Partial mocks](docs/GUIDE.md#partial-mocks). ## Names that conflict with the library: the symbol API *Applies to: 1.x and the betas (the symbols are new in 2.0.1).* @@ -165,7 +165,7 @@ The package exports symbols for its methods: `received`, `didNotReceive`, `clear * `clearReceivedCalls`, `mimick` and `configure` exist **only** as symbols. * In TypeScript, if a type has a member called `received`, `didNotReceive`, `returns`, `throws`, `resolves`, `rejects` or `mimicks`, its substitute offers only `sub[received]()` and `sub[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`, `rejects` or `mimicks` is now a setup, and passes silently.** In 1.x and the betas, `sub.received(1).returns(5)` was a check of a member called `returns`. Now `sub.received(1)` followed by `.returns(...)` configures a member of your own called `received` (see [Names that conflict with the library](README.md#in-javascript)). Search your tests for `received(...).returns(`, `.throws(`, `.resolves(`, `.rejects(` and `.mimicks(`, and use the symbol: `sub[received](1).returns(5)`. +* **In JavaScript, a string check of a member called `returns`, `throws`, `resolves`, `rejects` or `mimicks` is now a setup, and passes silently.** In 1.x and the betas, `sub.received(1).returns(5)` was a check of a member called `returns`. Now `sub.received(1)` followed by `.returns(...)` configures a member of your own called `received` (see [Names that conflict with the library](docs/GUIDE.md#in-javascript)). Search your tests for `received(...).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` offers `sub.received()` and `sub.didNotReceive()`, as in 2.0.0-beta.4, while for `T extends Account`, where `Account` has a member with one of these names, only the symbols are offered. @@ -203,8 +203,8 @@ If a test relied on `undefined` after the sequence, add it to the sequence where 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 when `info('hi')` was not called on `app.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 after `app.repo('users').save(1)`, `app.repo(Arg.any()).didNotReceive().save(1)` fails and `app.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](README.md#through-a-call-with-matchers)). When a matching received call was answered with a value that is not a substitute, such as the promise of `api.load(Arg.any()).resolves(user)`, the calls on that value cannot be counted there, so such a check throws a `SubstituteException` that 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 as `io.to('room-b').received(1).emit('message', Arg.any())` or a knex-style `db('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 only `io.to('room-a')`, and when calls with other arguments got the same substitute, too, it throws a `SubstituteException` that 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 whose `where()` returns the builder (`query.where(Arg.all()).returns(query)`) or a cycle does, is matched step by step: after the code's `db('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). After `io[clearReceivedCalls]()`, the calls that came through hand-outs made before the clear no longer count through `io`'s route. When the setup returns the substitute itself (`io.to(Arg.any()).returns(io)`, a fluent `return 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](README.md#through-a-call-with-matchers). +* **Nested checks really check.** In 1.x and the betas, `app.logger.received().info('hi')` passed whatever had been called. Now it fails when `info('hi')` was not called on `app.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 after `app.repo('users').save(1)`, `app.repo(Arg.any()).didNotReceive().save(1)` fails and `app.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](docs/GUIDE.md#through-a-call-with-matchers)). When a matching received call was answered with a value that is not a substitute, such as the promise of `api.load(Arg.any()).resolves(user)`, the calls on that value cannot be counted there, so such a check throws a `SubstituteException` that 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 as `io.to('room-b').received(1).emit('message', Arg.any())` or a knex-style `db('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 only `io.to('room-a')`, and when calls with other arguments got the same substitute, too, it throws a `SubstituteException` that 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 whose `where()` returns the builder (`query.where(Arg.all()).returns(query)`) or a cycle does, is matched step by step: after the code's `db('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). After `io[clearReceivedCalls]()`, the calls that came through hand-outs made before the clear no longer count through `io`'s route. When the setup returns the substitute itself (`io.to(Arg.any()).returns(io)`, a fluent `return 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](docs/GUIDE.md#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. ```js @@ -217,7 +217,7 @@ app.logger.received().info('hi') app.logger.received().info('bye') // throws SubstituteException ``` -In TypeScript, nested auto-substitutes are not typed as substitutes; see the [README](README.md#auto-substitutes-and-nested-members) 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).received(1).save(1)`. +In TypeScript, nested auto-substitutes are not typed as substitutes; see the [README](docs/GUIDE.md#auto-substitutes-and-nested-members) 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).received(1).save(1)`. ### Calls with argument matchers are setups *Applies to: 1.x and the betas.* @@ -235,12 +235,12 @@ 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, `Map`s and `Set`s 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](README.md#matchers-inside-objects-and-arrays). +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, `Map`s and `Set`s 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](docs/GUIDE.md#matchers-inside-objects-and-arrays). ### Match order *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](README.md#match-order). +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](docs/GUIDE.md#match-order). ```typescript @@ -272,9 +272,9 @@ console.log(calculator.add(1, 3)) // prints 1337 *Applies 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 a `mimicks()` function gets their first argument as `this`. So a wrapper that forwards with `fn.apply(this, args)` (retry, `once` and 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: after `api.getUser(1).name.returns('bob')`, `withRetry(api.getUser)(1).name` is `'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 called `call`, `apply` or `bind`, and a setup such as `client.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 own `client.rpc.call('getUser', 1)`, an unconfigured invocation returns an auto-substitute of its own, not the direct call's. See [`call`, `apply` and `bind`](README.md#call-apply-and-bind). +* `.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 a `mimicks()` function gets their first argument as `this`. So a wrapper that forwards with `fn.apply(this, args)` (retry, `once` and 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: after `api.getUser(1).name.returns('bob')`, `withRetry(api.getUser)(1).name` is `'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 called `call`, `apply` or `bind`, and a setup such as `client.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 own `client.rpc.call('getUser', 1)`, an unconfigured invocation returns an auto-substitute of its own, not the direct call's. See [`call`, `apply` and `bind`](docs/GUIDE.md#call-apply-and-bind). * 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()` in `app.getCalculator().add(1, 2).returns(99)`, are not recorded, also when `getCalculator()` is configured to return a substitute (but not when it returns the substitute it is called on, as a fluent `return this` does). Before, they were received calls, so `app.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 as `this`, as in `Reflect.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](README.md#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. +* 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, also when `getCalculator()` is configured to return a substitute (but not when it returns the substitute it is called on, as a fluent `return this` does). Before, they were received calls, so `app.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 as `this`, as in `Reflect.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](docs/GUIDE.md#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. ```typescript @@ -290,9 +290,9 @@ calculator.received().subtract(Arg.all()) // throws SubstituteException ### `new` is a call *Applies 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 ApiClient>()`; see [Creating a substitute](README.md#creating-a-substitute). +`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 ApiClient>()`; see [Creating a substitute](docs/GUIDE.md#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](README.md#classes-that-extend-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](docs/GUIDE.md#classes-that-extend-a-substitute). ```js const { Substitute, Arg } = require('@fluffy-spoon/substitute') @@ -334,9 +334,9 @@ calculator.received(1.5).add(1, 2) // throws SubstituteException: Expected count ### Checks that fail later *Applies 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](README.md#assertions-that-fail-later), which also lists how each test runner reports such a failure. +`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](docs/GUIDE.md#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](README.md#received-and-didnotreceive) and [Names that conflict with the library](README.md#in-javascript). 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`. +**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](docs/GUIDE.md#received-and-didnotreceive) and [Names that conflict with the library](docs/GUIDE.md#in-javascript). 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`. ```js @@ -360,18 +360,18 @@ Checks that fail later (these two, and a property-style `sub.received(2).member` * **JavaScript:** `Arg.any(type)` and `Arg.any.not(type)` throw a `TypeError` right 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, and `Arg.any.not('strnig')` matched every value. `'bigint'` is a documented type name now (it already matched `bigint` values). * **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 a `SubstituteException`: `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 for `Arg.any.not`, `Arg.is`, `Arg.is.not` and `Arg.all`). Before, such a setup never answered, and such a `didNotReceive()` check always passed. * An `Arg.is()` predicate that returns a promise or another thenable (an `async` predicate) throws a `TypeError` where 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 up `returns()` sequences, and its assignments are not made. Before, a predicate that read `user.name` of a substitute `user` recorded that read, so a later `user.received(1).name` failed, 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 (an `async` callback that it calls is recorded after its first `await`; drive such callbacks with `mimicks()`). 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 a `mimicks()` function to call such a callback (see [Matching specific arguments](README.md#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: a `didNotReceive()` check with one passed whatever was called, and a setup with one never answered. `Arg` matchers work inside them (`expect.objectContaining({ id: Arg.any() })`) and in the equality of jest and vitest (`expect(order).toEqual({ id: Arg.any() })`, where `Arg.all()` stands for one value), but not inside sinon's matchers, nor as the property matchers of snapshots (use `expect.any(String)` there). See [Matchers of test runners](README.md#matchers-of-test-runners). +* What an `Arg.is()` predicate does to a substitute argument leaves no trace: its reads and calls are not recorded and do not use up `returns()` sequences, and its assignments are not made. Before, a predicate that read `user.name` of a substitute `user` recorded that read, so a later `user.received(1).name` failed, 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 (an `async` callback that it calls is recorded after its first `await`; drive such callbacks with `mimicks()`). 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 a `mimicks()` function to call such a callback (see [Matching specific arguments](docs/GUIDE.md#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: a `didNotReceive()` check with one passed whatever was called, and a setup with one never answered. `Arg` matchers work inside them (`expect.objectContaining({ id: Arg.any() })`) and in the equality of jest and vitest (`expect(order).toEqual({ id: Arg.any() })`, where `Arg.all()` stands for one value), but not inside sinon's matchers, nor as the property matchers of snapshots (use `expect.any(String)` there). See [Matchers of test runners](docs/GUIDE.md#matchers-of-test-runners). * **JavaScript:** `mimicks()` with something other than a function (or with nothing) throws a `TypeError` at 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`). ### How arguments are compared *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](README.md#how-arguments-are-compared)). +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](docs/GUIDE.md#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](README.md#how-arguments-are-compared)). +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](docs/GUIDE.md#how-arguments-are-compared)). ```typescript @@ -391,7 +391,7 @@ console.log(repository.save({ name: 'bob' })) // prints saved ### Omitted arguments *Applies 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](README.md#how-arguments-are-compared). So: +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](docs/GUIDE.md#how-arguments-are-compared). So: * `users.find(Arg.any('undefined')).returns(...)` and `users.find(Arg.any()).returns(...)` now answer `users.find()`, and `received(1).find(Arg.any())` counts it. * **`didNotReceive().f(Arg.any())` now fails after `f()`**, and `received(count).log(Arg.any(), Arg.all())` counts `log()` as well. @@ -418,11 +418,11 @@ A `mimicks()` function is called with the `this` of the call, like a method: the ### Protocol members read as `undefined` *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](README.md#special-members)). Before, they returned auto-substitutes. So: +`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](docs/GUIDE.md#special-members)). Before, they returned auto-substitutes. So: * `[].concat(sub)` keeps the substitute as one element (it was dropped), `value instanceof sub.SomeClass` is `false` (it was `true`), `'text'.startsWith(sub.prefix)` no longer throws, and `util.promisify(sub.readFile)` calls the substitute, on every supported Node.js version (the running Node.js' own `util.promisify.custom` is handled too; on Node.js 10.0 to 12.16.1 and 13.0 to 13.11 it is not `Symbol.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: ()]` (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](README.md#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-substitute `handleEvent` instead. Code under test that calls `handleEvent` of a substitute itself now needs it configured or mimicked; see [Substitutes are functions](README.md#substitutes-are-functions). +* 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: ()]` (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](docs/GUIDE.md#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-substitute `handleEvent` instead. Code under test that calls `handleEvent` of a substitute itself now needs it configured or mimicked; see [Substitutes are functions](docs/GUIDE.md#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`, `.calledOnce` and `.calledWith('x')` passed on a substitute that was never called. See [Spy assertions of jest and sinon-chai](#spy-assertions-of-jest-and-sinon-chai). * jest no longer takes a substitute for an asymmetric matcher. Before, `expect(fn).toHaveBeenCalledWith(sub)` and `expect(list).toContainEqual(sub)` passed whatever the arguments or items were, and a failing `expect(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...of` and `Promise.all(sub)` on a substitute that is not configured throw a `TypeError`. In the betas they treated it as empty; in 1.x they threw a different `TypeError`. Configure the iterator, or mimick an array: @@ -441,18 +441,18 @@ 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](README.md#mocking-a-whole-module) for each runner. +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](docs/GUIDE.md#mocking-a-whole-module) for each runner. ### Freezing, defined properties and `in` *Applies to: 1.x and the betas.* * `Object.freeze()`, `Object.seal()` and `Object.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 a `TypeError` ("Cannot add property _child, object is not extensible"). In 1.x, reads, setups and checks kept working, except that reading `length` or `name` afterwards threw a `TypeError` (a proxy invariant error), as reading `prototype` always did. -* `Object.defineProperty(sub, key, descriptor)` defines a real property, which reads return without recording them. Before, it threw a `TypeError`. On a substitute that mimicks an object, it defines the member on the instance, as an assignment writes to it, and `delete sub.key` deletes the instance's member (see [Partial mocks](README.md#partial-mocks)), except for a descriptor with `configurable: false`, or without `configurable` for a key that the instance does not have as its own (as on any object, the default is then `false`): that defines a property of the substitute itself, which reports it and refuses to redefine it, as a plain object does. +* `Object.defineProperty(sub, key, descriptor)` defines a real property, which reads return without recording them. Before, it threw a `TypeError`. On a substitute that mimicks an object, it defines the member on the instance, as an assignment writes to it, and `delete sub.key` deletes the instance's member (see [Partial mocks](docs/GUIDE.md#partial-mocks)), except for a descriptor with `configurable: false`, or without `configurable` for a key that the instance does not have as its own (as on any object, the default is then `false`): 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 checks `instanceof`, keeps the substitute working: reads, calls, assignments, setups, checks, the symbols, `String()` and `JSON.stringify()` work as before. Only `util.inspect()` shows it as `[Function: bound substitute] EventEmitter` then, also where it is an argument in a failure message. In 2.0.0-beta.4, checks, assignments and `String(sub)` threw a `TypeError` afterwards, such as `target.isSpecialProperty is not a function`. On a frozen, sealed or non-extensible substitute, `Object.setPrototypeOf()` with another prototype throws a `TypeError` that 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 does `Reflect.setPrototypeOf()`, which returned `false` in 2.0.0-beta.4. -* A substitute has no enumerable own properties: `Object.keys(sub)` is empty, and `Reflect.ownKeys(sub)` is `[ 'length', 'name' ]`, the non-enumerable properties that every function has (`length` is `0`, and `name` is the member's name for a member, such as `'getKey'` for `keys.getKey`, and `''` for a substitute itself), unless it mimicks an object: then `Object.keys()`, `Object.entries()`, spread, `Object.assign()` and `for...in` see the instance's enumerable own keys, and `JSON.stringify(sub)` gives what `JSON.stringify(instance)` gives (see [Partial mocks](README.md#partial-mocks)). In the betas, `Object.keys(sub)` listed internal fields such as `_key` and `_recorder`, and in 1.x and the betas, `Reflect.ownKeys(sub)` listed `length`, `name` and `prototype` of the library's internal function, with its internal name. Reading `sub.name` or `sub.length` is a member read, as before. `util.callbackify(sub.method)` works, except for a substitute that was frozen, sealed or made non-extensible, which lists no `length` and `name`: wrap such a substitute in a function (`util.callbackify((...args) => frozen(...args))`). See [Freezing, defined properties and `in`](README.md#freezing-defined-properties-and-in). +* A substitute has no enumerable own properties: `Object.keys(sub)` is empty, and `Reflect.ownKeys(sub)` is `[ 'length', 'name' ]`, the non-enumerable properties that every function has (`length` is `0`, and `name` is the member's name for a member, such as `'getKey'` for `keys.getKey`, and `''` for a substitute itself), unless it mimicks an object: then `Object.keys()`, `Object.entries()`, spread, `Object.assign()` and `for...in` see the instance's enumerable own keys, and `JSON.stringify(sub)` gives what `JSON.stringify(instance)` gives (see [Partial mocks](docs/GUIDE.md#partial-mocks)). In the betas, `Object.keys(sub)` listed internal fields such as `_key` and `_recorder`, and in 1.x and the betas, `Reflect.ownKeys(sub)` listed `length`, `name` and `prototype` of the library's internal function, with its internal name. Reading `sub.name` or `sub.length` is a member read, as before. `util.callbackify(sub.method)` works, except for a substitute that was frozen, sealed or made non-extensible, which lists no `length` and `name`: wrap such a substitute in a function (`util.callbackify((...args) => frozen(...args))`). See [Freezing, defined properties and `in`](docs/GUIDE.md#freezing-defined-properties-and-in). * `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. Before, it answered for the library's internal function: `true` for `call`, `length` and the other members of functions, and `false` for configured members. Code under test that checks for an optional member with `in` now takes the branch that the test configured. -See [Freezing, defined properties and `in`](README.md#freezing-defined-properties-and-in). +See [Freezing, defined properties and `in`](docs/GUIDE.md#freezing-defined-properties-and-in). ### Messages *Applies to: 1.x and the betas.* @@ -464,7 +464,7 @@ The wording of `SubstituteException` messages changed, for example "Expected to ### Printing *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: ` or `method: (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, `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, 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](README.md#printing-a-substitute). +`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: ` or `method: (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, `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, 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](docs/GUIDE.md#printing-a-substitute). ```js const { Substitute } = require('@fluffy-spoon/substitute') @@ -484,7 +484,7 @@ console.log(JSON.stringify({ user: app.getUser(1) })) // prints {"user":"@Substi * 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(...)`) throw `RangeError: Maximum call stack size exceeded` for a substitute: to find the spy, sinon follows `proxy` and `isSinonProxy`, 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's `mock.method(sub, 'fetch')` throw a `TypeError` (`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 with `returns()` or `mimicks()` instead, or spy on a reference to it: `sinon.spy(sub.save)` and `mock.fn(sub.fetch)` call the substitute, whose setups answer and whose checks count those calls. vitest's `vi.spyOn(sub, 'fetch')` works for a member that has a setup; for one without, it throws `Error: 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](README.md#partial-mocks) an object, a method that the instance has as its own property has a property descriptor, so `jest.spyOn()`, `vi.spyOn()`, `mock.method()` and `sinon.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's `mock.method()` with an implementation, too: the setups answer first, the mock's implementation answers the other calls, and reads of `sub.stat` give the member handle (whose `mock` is the mock's context), not the mock. The instance's own calls of such a member through `this` stay 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)`), and `sinon.spy(sub, 'stat')` and `sinon.stub(sub, 'stat')` throw `TypeError: Attempted to wrap stat which is already wrapped`. For a method on the prototype of a class instance, `mock.method()` and sinon's `replace()`, `spy()` and `stub()` 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](README.md#test-runners) for each tool, also on a frozen instance. Before, `mock.method()`, `vi.spyOn()`, `sinon.spy()` and `sinon.stub()` silently wrapped the instance's own function, so the setups and checks of the substitute did not see those calls, and `jest.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. +* On a substitute that [mimicks](docs/GUIDE.md#partial-mocks) an object, a method that the instance has as its own property has a property descriptor, so `jest.spyOn()`, `vi.spyOn()`, `mock.method()` and `sinon.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's `mock.method()` with an implementation, too: the setups answer first, the mock's implementation answers the other calls, and reads of `sub.stat` give the member handle (whose `mock` is the mock's context), not the mock. The instance's own calls of such a member through `this` stay 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)`), and `sinon.spy(sub, 'stat')` and `sinon.stub(sub, 'stat')` throw `TypeError: Attempted to wrap stat which is already wrapped`. For a method on the prototype of a class instance, `mock.method()` and sinon's `replace()`, `spy()` and `stub()` 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](docs/GUIDE.md#test-runners) for each tool, also on a frozen instance. Before, `mock.method()`, `vi.spyOn()`, `sinon.spy()` and `sinon.stub()` silently wrapped the instance's own function, so the setups and checks of the substitute did not see those calls, and `jest.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 | |---|---| @@ -496,7 +496,7 @@ console.log(JSON.stringify({ user: app.getUser(1) })) // prints {"user":"@Substi | `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](README.md#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`. +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](docs/GUIDE.md#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`. ```js const { Substitute, Arg } = require('@fluffy-spoon/substitute') @@ -512,7 +512,7 @@ next.received(1)(Arg.is(error => error instanceof Error && error.message === 'bo next.didNotReceive()(Arg.all()) // throws SubstituteException ``` -See [Test runners](README.md#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()`. +See [Test runners](docs/GUIDE.md#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()`. ## Imports and packaging *Applies to: 1.x and the betas.* @@ -528,9 +528,9 @@ calculator.add(Arg.any(), 2).returns(3) console.log(calculator.add(1, 2)) // prints 3 ``` -Bundles 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](README.md#importing). +Bundles 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](docs/GUIDE.md#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 `import`s the package, are not affected by this. See [Importing](README.md#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 `import`s the package, are not affected by this. See [Importing](docs/GUIDE.md#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/`: @@ -566,25 +566,25 @@ The typings were reworked. Most code compiles unchanged, but: * The [symbol rules](#names-that-conflict-with-the-library-the-symbol-api) 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` for a generic `T`. In generic code, the string forms `sub.received()` and `sub.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 called `received`, `didNotReceive`, `returns`, `throws`, `resolves`, `rejects` or `mimicks`, 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(sub: SubstituteOf)`, or a fixture class `Fixture` with `sub = Substitute.for()`), setups, checks and the `configure` view work through the constraint: `sub.total.returns(1)`, `sub.add(1, 2).returns(3)`, `sub.received().total = 1` and `sub[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](README.md#typing-limitations)): +* With a constrained type parameter (`function stub(sub: SubstituteOf)`, or a fixture class `Fixture` with `sub = Substitute.for()`), setups, checks and the `configure` view work through the constraint: `sub.total.returns(1)`, `sub.add(1, 2).returns(3)`, `sub.received().total = 1` and `sub[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](docs/GUIDE.md#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 includes `null` or `undefined` have none either, and neither do `maybe?: T` or `orNull: T | null` of any type parameter, constrained or not, in an interface such as `Box`. Configure them through `sub[configure]()`, which works on every version. * A union constraint whose variants' methods return different types (`T extends Cat | Dog`, with `speak(): 'meow'` and `speak(): 'woof'`): `.returns()` takes `never` there. Cast to the constraint: `(pet as SubstituteOf).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`, with `log(message: string): void` and `log(message: string, level?: number): void`) has no setup API, even when every variant returns the same type. Use the `configure` view (`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` with `T extends Repo`) has no `.resolves()` or `.rejects()` (string form, symbol form or `configure` view), while promise-returning methods have them. Write `repo.name.returns(Promise.resolve(value))`, or `.returns(Promise.reject(error))`, which work on every supported version. Concrete types are not affected. * 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()` with `load(): Promise` and `load(): Promise`, or methods that return `this`), 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 the `configure` view. With 2.0.0-beta.4, `.resolves()` on such methods, and `.returns()` on methods that return `this` and on union-typed callback members, took `never`, 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')` for `fetch(url)` and `fetch(url, options?)` in `Substitute.for()`, and `reader.read('p').returns('text')` and `.returns(new Uint8Array())` for `read(path): string` and `read(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')` for `move(x: string, y: number)` and `move(x: number, y: string)`) 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 (`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](README.md#typing-limitations) has the exact rule, and the cases that need a cast to one variant (such as `Arg.any()` where the variants' parameter types differ). With 2.0.0-beta.4, `.returns()` on such methods 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. 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. +* 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')` for `fetch(url)` and `fetch(url, options?)` in `Substitute.for()`, and `reader.read('p').returns('text')` and `.returns(new Uint8Array())` for `read(path): string` and `read(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')` for `move(x: string, y: number)` and `move(x: number, y: string)`) 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 (`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](docs/GUIDE.md#typing-limitations) has the exact rule, and the cases that need a cast to one variant (such as `Arg.any()` where the variants' parameter types differ). With 2.0.0-beta.4, `.returns()` on such methods 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. 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 [`new`](#new-is-a-call) needs: `Client('https://api').returns(client)` and `Client.received(1)('https://api')` for `Substitute.for ApiClient>()`, and `sdk.Client(Arg.any()).returns(client)` and `sdk.received(1).Client('https://api')` for a member `Client: 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` and its subtypes without members of their own (such as Prisma's `PrismaPromise`, which only narrows `[Symbol.toStringTag]`), `PromiseLike`, and unions such as `void | Promise` or `string | Promise`. 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 { where(...): Query }`), nor for a subtype of `Promise` with members of its own, such as ky's `ResponsePromise` (`json()`, `text()`), knex's `QueryBuilder` (`where()`), execa's result (`kill()`) or a `CancellablePromise` with `cancel()`: a native promise has no such members. **2.0.0-beta.4 offered them for such `Promise` subtypes**, 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](README.md#working-with-promises). +* `.resolves()` and `.rejects()` configure a native promise, and are offered on every member that a native promise of the value fits: `Promise` and its subtypes without members of their own (such as Prisma's `PrismaPromise`, which only narrows `[Symbol.toStringTag]`), `PromiseLike`, and unions such as `void | Promise` or `string | Promise`. 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 { where(...): Query }`), nor for a subtype of `Promise` with members of its own, such as ky's `ResponsePromise` (`json()`, `text()`), knex's `QueryBuilder` (`where()`), execa's result (`kill()`) or a `CancellablePromise` with `cancel()`: a native promise has no such members. **2.0.0-beta.4 offered them for such `Promise` subtypes**, 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](docs/GUIDE.md#working-with-promises). * `.returns()` and `.resolves()` (also `[returns]()`, `[resolves]()` and the `configure` view) can be called without a value whenever `undefined` is a valid value: for `any`, `unknown`, `void`, `undefined` and `T | undefined`, as in Koa's `next().resolves()` or `repo.findById('42').resolves()` for `Promise`. With 2.0.0-beta.4, only a `void` value could be left out. -* Generic methods (`get(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')` for `same(a: T, b: T): T` takes `string | number`). On Node.js' `EventEmitter`, `Arg.all()` after the leading arguments of `emit()` (`orders.received(1).emit('paid', Arg.all())`) compiles, with the leading arguments checked against `emit()`'s own signature, with `@types/node` 18.19.63 to 24.x; from `@types/node` 25 on, `emit()` takes any event and any arguments on a substitute, and an untyped `Arg.is()` predicate gets `any` there. An `Arg.is()` predicate in the arguments of a typed emitter's `emit()` needs a parameter type (`Arg.is((orderId: string) => ...)`), and a type parameter's default is not used, so pino's `logger.child(...)` takes a `Logger` in `.returns()`. A call with too many or too few arguments is rejected, except for Node.js' `EventEmitter.emit`, and, on TypeScript 3.6 to 3.9, for generic methods whose rest parameter is typed by an indexed access (`send(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(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](README.md#typing-limitations). +* Generic methods (`get(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')` for `same(a: T, b: T): T` takes `string | number`). On Node.js' `EventEmitter`, `Arg.all()` after the leading arguments of `emit()` (`orders.received(1).emit('paid', Arg.all())`) compiles, with the leading arguments checked against `emit()`'s own signature, with `@types/node` 18.19.63 to 24.x; from `@types/node` 25 on, `emit()` takes any event and any arguments on a substitute, and an untyped `Arg.is()` predicate gets `any` there. An `Arg.is()` predicate in the arguments of a typed emitter's `emit()` needs a parameter type (`Arg.is((orderId: string) => ...)`), and a type parameter's default is not used, so pino's `logger.child(...)` takes a `Logger` in `.returns()`. A call with too many or too few arguments is rejected, except for Node.js' `EventEmitter.emit`, and, on TypeScript 3.6 to 3.9, for generic methods whose rest parameter is typed by an indexed access (`send(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(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](docs/GUIDE.md#typing-limitations). * `Arg.any('bigint')` is typed `bigint`. * `sub[mimick](instance)` takes a partial instance of an object type (`client[mimick]({ baseUrl: '' })` for a `Client` with 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 a `T` (also for a substitute of `T | undefined` or `T | null`). In an object literal, `this` is the partial type, so a fluent method casts it: `res[mimick]({ status() { return this as Response } })`. 2.0.0-beta.4 had only the string `mimick(instance)`, which took a whole instance (see [the string `mimick(instance)`](#the-string-mimickinstance)). -* `Arg.any('string')` is typed `string`, as with 2.0.0-beta.4 (and `Arg.any('number')` `number`, and so on), so overloads such as Node.js' `on(event: 'close', ...)` next to `on(event: string, ...)`, or lib.dom's `querySelector()`, 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()`. Write `Arg.is((currency: Currency) => true)` or `Arg.any('string') as Currency` there (`as unknown as OrderId` for a branded type). See [Matching by type](README.md#matching-by-type). -* Overloaded generic methods whose parameter types depend on a type parameter through a conditional type, such as `@types/pg`'s `Pool.query` and `ClientBase.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 values `as 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](README.md#typing-limitations). -* On an overloaded method whose overloads return different types, a setup with `Arg.all()` alone takes any overload's value, so `pool.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`'s `query(text, values?)` and `query(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) => ...` for `get()` next to `get(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 for `pool.query()`). On overloads whose return types depend on their type parameters, such as TypeORM's `Repository.save()`, an untyped parameter of a `mimicks()` function is typed with the constraints (`DeepPartial[] | DeepPartial`), 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 with `Arg.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: use `Arg.all()`, a typed `Arg.is((saved: User) => ...)`, `Arg.any() as User` or a value. Where the argument's type only contains the type parameters, as in AWS SDK v3's `s3.send(command)`, it is the other way round under `strict`: `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), because `Command` is invariant in its type parameters. Checks take every form. See [Typing limitations](README.md#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). See [Ignoring all arguments](README.md#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.get` and `Context.set` with an empty `ContextVariableMap`, has the setup API now: `c.get('user').returns(user)`, `c[configure]().get('user').returns(user)` and `c.get(Arg.all()).returns(user)` compile (with 2.0.0-beta.4, only `c.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 the `Context` type. Only such a last overload that returns `never` once its type parameters are replaced is left out; [Typing limitations](README.md#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 through `unknown`, 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).received(1).save(1)`. See [Through a call with matchers](README.md#through-a-call-with-matchers). +* `Arg.any('string')` is typed `string`, as with 2.0.0-beta.4 (and `Arg.any('number')` `number`, and so on), so overloads such as Node.js' `on(event: 'close', ...)` next to `on(event: string, ...)`, or lib.dom's `querySelector()`, 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()`. Write `Arg.is((currency: Currency) => true)` or `Arg.any('string') as Currency` there (`as unknown as OrderId` for a branded type). See [Matching by type](docs/GUIDE.md#matching-by-type). +* Overloaded generic methods whose parameter types depend on a type parameter through a conditional type, such as `@types/pg`'s `Pool.query` and `ClientBase.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 values `as 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](docs/GUIDE.md#typing-limitations). +* On an overloaded method whose overloads return different types, a setup with `Arg.all()` alone takes any overload's value, so `pool.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`'s `query(text, values?)` and `query(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) => ...` for `get()` next to `get(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 for `pool.query()`). On overloads whose return types depend on their type parameters, such as TypeORM's `Repository.save()`, an untyped parameter of a `mimicks()` function is typed with the constraints (`DeepPartial[] | DeepPartial`), 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 with `Arg.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: use `Arg.all()`, a typed `Arg.is((saved: User) => ...)`, `Arg.any() as User` or a value. Where the argument's type only contains the type parameters, as in AWS SDK v3's `s3.send(command)`, it is the other way round under `strict`: `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), because `Command` is invariant in its type parameters. Checks take every form. See [Typing limitations](docs/GUIDE.md#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). See [Ignoring all arguments](docs/GUIDE.md#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.get` and `Context.set` with an empty `ContextVariableMap`, has the setup API now: `c.get('user').returns(user)`, `c[configure]().get('user').returns(user)` and `c.get(Arg.all()).returns(user)` compile (with 2.0.0-beta.4, only `c.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 the `Context` type. Only such a last overload that returns `never` once its type parameters are replaced is left out; [Typing limitations](docs/GUIDE.md#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 through `unknown`, 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).received(1).save(1)`. See [Through a call with matchers](docs/GUIDE.md#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 a `boolean`. * A member called `then` is typed `never`: substitutes are never thenables. * Members typed only `null` or `undefined` (`error?: undefined`, `ownerDocument: null`) keep their plain type and no longer have `.returns()` and the other setup methods. Configure them through `sub[configure]()`. In a union, a member that is only `null` or `undefined` in 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 `: null` form turned the substitute into `never` (on TypeScript 3.9 and newer); the `?: undefined` form compiled with 2.0.0-beta.4. @@ -593,5 +593,5 @@ The typings were reworked. Most code compiles unchanged, but: * `Arg.any('undefined')` only fits parameters and properties that accept `undefined`, such as an optional parameter, `number | undefined` or `unknown`. It was typed `never`, which fit every parameter, so code like `calculator.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 return `never`, `Arg.all()` after other arguments (after up to 6 of them), and types with very large unions of string literals, such as lib.dom's `HTMLInputElement`. * An optional function-typed property (`onChange?: (value: string) => void`) does not accept `undefined` in a check. Write `(widget.received() as Widget).onChange = undefined`, or `widget.received().onChange = Arg.any.not('function')`. -* In a project compiled with `declaration: true` (or `composite: 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 the `configure` view: 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' `EventEmitter` and streams) can be exported, too. The type of a check view is exported as `CheckViewOf`, so a generic helper that returns one, in the string or the symbol form, is annotated as `function once(sub: SubstituteOf): CheckViewOf { return sub[received](1) }`, also with `isolatedDeclarations` (`ReturnType['received']>` does not compile in generic code). A generic helper 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, needs a type annotation (`function optional(sub: SubstituteOf): SubstituteOf`, `CheckViewOf` 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 with `moduleResolution: node` by TypeScript 5.9 and older, refers to the directory `@fluffy-spoon/substitute/dist/shared`, which the package's `exports` map to its index, so `node16`, `nodenext` and `bundler` projects read it with full types. See [Typing limitations](README.md#typing-limitations). -* See [Typing limitations](README.md#typing-limitations) for what TypeScript cannot express. +* In a project compiled with `declaration: true` (or `composite: 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 the `configure` view: 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' `EventEmitter` and streams) can be exported, too. The type of a check view is exported as `CheckViewOf`, so a generic helper that returns one, in the string or the symbol form, is annotated as `function once(sub: SubstituteOf): CheckViewOf { return sub[received](1) }`, also with `isolatedDeclarations` (`ReturnType['received']>` does not compile in generic code). A generic helper 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, needs a type annotation (`function optional(sub: SubstituteOf): SubstituteOf`, `CheckViewOf` 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 with `moduleResolution: node` by TypeScript 5.9 and older, refers to the directory `@fluffy-spoon/substitute/dist/shared`, which the package's `exports` map to its index, so `node16`, `nodenext` and `bundler` projects read it with full types. See [Typing limitations](docs/GUIDE.md#typing-limitations). +* See [Typing limitations](docs/GUIDE.md#typing-limitations) for what TypeScript cannot express. diff --git a/README.md b/README.md index 3997f9d3..a6c46566 100644 --- a/README.md +++ b/README.md @@ -1,4339 +1,346 @@ -Financial Contributors on Open Collective +
-# What is this? -[`@fluffy-spoon/substitute`](https://www.npmjs.com/package/@fluffy-spoon/substitute) is a TypeScript port of [NSubstitute](http://nsubstitute.github.io), which aims to provide a much more fluent mocking opportunity for strong-typed languages. +# 🥄 substitute.js -*You can read an in-depth comparison of `substitute.js` versus other popular TypeScript mocking frameworks here: https://medium.com/@mathiaslykkegaardlorenzen/with-typescript-3-and-substitute-js-you-are-already-missing-out-when-mocking-or-faking-a3b3240c4607 (written for version 1; the ideas still apply).* +**Strongly typed, fluent mocking for TypeScript and JavaScript, inspired by [NSubstitute](https://nsubstitute.github.io).** -**PRs are very welcome! Help is much appreciated.** +[![npm version](https://img.shields.io/npm/v/@fluffy-spoon/substitute.svg)](https://www.npmjs.com/package/@fluffy-spoon/substitute) +[![npm downloads](https://img.shields.io/npm/dm/@fluffy-spoon/substitute.svg)](https://www.npmjs.com/package/@fluffy-spoon/substitute) +[![CI](https://github.com/ffMathy/FluffySpoon.JavaScript.Testing.Faking/actions/workflows/nodejs.yml/badge.svg)](https://github.com/ffMathy/FluffySpoon.JavaScript.Testing.Faking/actions/workflows/nodejs.yml) +[![license: MIT](https://img.shields.io/npm/l/@fluffy-spoon/substitute.svg)](LICENSE) +[![Financial Contributors on Open Collective](https://opencollective.com/substitute-js/all/badge.svg?label=financial+contributors)](https://opencollective.com/substitute-js#section-contribute) -> Upgrading from 1.x or from a 2.0.0 beta? Read the [migration guide](MIGRATION.md). What changed in each version is in the [changelog](CHANGELOG.md). +[Quick start](#quick-start) · [Cheat sheet](#cheat-sheet) · [Full guide](docs/GUIDE.md) · [Migrating from 1.x](MIGRATION.md) · [Changelog](CHANGELOG.md) -# Table of contents -- [Installing](#installing) · [Requirements](#requirements) · [Importing](#importing) -- [Usage](#usage): [creating a substitute](#creating-a-substitute), [return values](#setting-return-values), [promises](#working-with-promises), [exceptions](#throwing-exceptions), [mimicking](#mimicking-an-implementation), [members that are a property and a method](#members-used-as-a-property-and-as-a-method), [classes that extend a substitute](#classes-that-extend-a-substitute) -- [Argument matchers](#argument-matchers), [inside objects and arrays](#matchers-inside-objects-and-arrays), [the matchers of test runners](#matchers-of-test-runners), [how arguments are compared](#how-arguments-are-compared) and [match order](#match-order) -- [Re-configuring a call](#re-configuring-a-call-configure) · [Partial mocks](#partial-mocks) · [Auto-substitutes](#auto-substitutes-and-nested-members), [fluent interfaces](#fluent-interfaces), [through a call with matchers](#through-a-call-with-matchers) and [which calls lead to a setup](#which-calls-lead-to-a-setup-or-a-check) -- [Verifying calls](#verifying-calls): [counts](#received-and-didnotreceive), [properties](#properties), [what counts as a call](#what-counts-as-a-call), [clearing](#clearing-received-calls), [SubstituteException](#substituteexception), [deferred failures](#assertions-that-fail-later) -- [Names that conflict with the library](#names-that-conflict-with-the-library), [`call`, `apply` and `bind`](#call-apply-and-bind) and [the symbol API](#the-symbol-api) -- [Special members](#special-members): [substitutes are functions](#substitutes-are-functions), [printing](#printing-a-substitute), [freezing and `in`](#freezing-defined-properties-and-in) · [Typing limitations](#typing-limitations) · [Test runners](#test-runners), [mocking a whole module](#mocking-a-whole-module) and [debuggers](#debuggers) +
-# Installing -```sh -npm install @fluffy-spoon/substitute --save-dev -``` - -This README describes version 2. Until 2.0.1, `npm install` installed 1.208.0 (the `latest` tag). If you depend on version 1, pin it with `npm install @fluffy-spoon/substitute@1 --save-dev`; its README is at the [v1.208.0 tag](https://github.com/ffMathy/FluffySpoon.JavaScript.Testing.Faking/tree/v1.208.0#readme). - -# Requirements -* Node.js 10 or newer for CommonJS (`require`). -* For the 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. Node.js 10.x, 12.0 to 12.16 and 13.0 to 13.1 have no ES modules without a flag, and 13.2 to 13.6 do not pick the package's ES module entry, so named imports fail there; use `require` on those versions. -* TypeScript 3.6 or newer, if you use TypeScript. `strict` mode, including `strictNullChecks`, is supported. -* Any test runner. ava, jest, mocha, node:test and vitest are tested on every change (see [Test runners](#test-runners)). - -# Importing -Prefer the named import, `import { Substitute, Arg } from '@fluffy-spoon/substitute'`: it works with every module system, bundler and loader. - -TypeScript, or code compiled by a bundler: - -```typescript -import { Substitute, Arg } from '@fluffy-spoon/substitute' -// or: import Substitute, { Arg } from '@fluffy-spoon/substitute' -// (but not in CommonJS bundles that keep the package external, or with ts-node's ESM loader; see below) -``` - -CommonJS: - -```js -const { Substitute, Arg } = require('@fluffy-spoon/substitute') - -const calculator = Substitute.for() -calculator.add(1, Arg.any()).returns(3) -console.log(calculator.add(1, 2)) // prints 3 -``` - -Native ES modules (`.mjs` files or `"type": "module"`). The default import is the `Substitute` class, and named imports work too: - - -```js -import Substitute, { Arg, received } from '@fluffy-spoon/substitute' - -const calculator = Substitute.for() -calculator.add(Arg.all()).returns(3) -console.log(calculator.add(1, 2)) // prints 3 -calculator[received](1).add(1, 2) -``` - -The ES module entry point wraps the CommonJS build, so both share one copy of the library. Bundlers that include the package in the bundle, or that emit ES modules, give the same exports: on every change, the package is bundled with Rollup and `@rollup/plugin-commonjs`, webpack, esbuild and a Vite SSR build with `ssr.noExternal`, and run in vitest with `server.deps.inline`, with and without `deps.interopDefault: false`. For esbuild's ES module output for Node.js (`format: 'esm'`, `platform: 'node'`), add the usual banner `import { createRequire } from 'module'; const require = createRequire(import.meta.url);`, because the library loads Node.js' `util` module with `require`. If a tool cannot hand the CommonJS exports to the ES module entry, `import` throws right away with an error that says so; use `require()` with that tool. - -Three setups need care. - -**CommonJS code that `require()`s the package, bundled with the package external.** This concerns CommonJS code bundled with Rollup's `@rollup/plugin-commonjs` while the package stays external, which Vite 7 and older do in SSR builds, because they keep dependencies external by default. With default options, the plugin turns that `require()` into a default import, which Node.js resolves to the ES module entry, so `require()` returns the `Substitute` class instead of the exports object. Nothing fails at that point, but `Substitute`, `Arg` and the other named exports are `undefined`, so `const { Substitute } = require('@fluffy-spoon/substitute')` followed by `Substitute.for()` throws `TypeError: Cannot read properties of undefined (reading 'for')`. Pass `commonjs({ esmExternals: true })` or `commonjs({ esmExternals: ['@fluffy-spoon/substitute'] })`, or bundle the package instead of keeping it external (in Vite: `ssr: { noExternal: ['@fluffy-spoon/substitute'] }`). In Vite 5 to 7, the plugin's option can also be passed as `build: { commonjsOptions: { esmExternals: ['@fluffy-spoon/substitute'] } }`. Vite 8 and newer are not affected by this, and neither is code that `import`s the package (but see the next paragraph for bundles with CommonJS output). On every change, the compatibility checks bundle such code with Rollup and each of the `commonjs()` settings above, with the package bundled, and with Vite's `ssr.noExternal`. - -**CommonJS output with the package external.** When a bundler compiles ES module code (or TypeScript) into CommonJS output and keeps the package external, the bundle loads the package with `require()`, and the default import follows Node.js' CommonJS interop: it is the exports object, not the `Substitute` class. The first use then throws, for example `TypeError: Substitute.for is not a function` (Rollup, Vite 7), `import_substitute.default.for is not a function` (esbuild), `_fluffy_spoon_substitute__WEBPACK_IMPORTED_MODULE_0__.for is not a function` (webpack) or `_fluffy_spoon_substitute.default.for is not a function` (Rolldown, Vite 8). This happens for every source file with Rollup and `output.format: 'cjs'`, and with the SSR builds of Vite 5 to 7 with `build.rollupOptions.output.format: 'cjs'`. It also happens for `.mjs` files, and for `.js` and `.ts` files in a package with `"type": "module"`, with esbuild (`format: 'cjs'` with the package external, for example `packages: 'external'`), with webpack (`target: 'node'` with a `commonjs` external, for example `externals: { '@fluffy-spoon/substitute': 'commonjs @fluffy-spoon/substitute' }`), with Rolldown (`format: 'cjs'`) and with the SSR builds of Vite 8 with `build.rolldownOptions.output.format: 'cjs'`. Use the named import there, which works in every setup: `import { Substitute, Arg } from '@fluffy-spoon/substitute'`. With Rollup, and Vite 5 to 7, `output.interop: 'auto'` (in Vite: `build.rollupOptions.output.interop: 'auto'`) also makes the default import work. ES module output, and bundles that include the package, are not affected. On every change, the compatibility checks bundle the named import into CommonJS output with Rollup, esbuild, webpack and a Vite SSR build, and check Rollup's `output.interop: 'auto'`. - -**ts-node's ESM loader.** With ts-node's ESM loader (`node --loader ts-node/esm`, also `mocha --loader=ts-node/esm`) and `module` and `moduleResolution` set to `node16` or `nodenext`, the default import does not type-check in `.mts` files and in `.ts` files of a package with `"type": "module"`. ts-node checks such a file against the package's CommonJS typings, so `import Substitute from '@fluffy-spoon/substitute'` followed by `Substitute.for()` is rejected with `error TS2339: Property 'for' does not exist on type 'typeof import(".../node_modules/@fluffy-spoon/substitute/dist/index")'`. ts-node does not show that message: the process exits with only `[Object: null prototype] { [Symbol(nodejs.util.inspect.custom)]: [Function: [nodejs.util.inspect.custom]] }` and the Node.js version. `tsc` accepts the same file. Use the named import, run the file with tsx (`node --import tsx`), or turn on ts-node's `transpileOnly` (`TS_NODE_TRANSPILE_ONLY=1`). - -Everything is exported from the package root: `Substitute`, `Arg`, `SubstituteException`, the types `SubstituteOf` and `CheckViewOf` (what `received()` and `didNotReceive()` return; see [Typing limitations](#typing-limitations), 'Declaration emit'), and the symbols `received`, `didNotReceive`, `clearReceivedCalls`, `mimick`, `configure`, `returns`, `throws`, `resolves`, `rejects` and `mimicks`. Paths inside the package (`@fluffy-spoon/substitute/dist/...`) are not public API and can change in any release. - -# Usage -The examples in this README use this interface: - - -```typescript -import { Substitute, Arg } from '@fluffy-spoon/substitute' - -interface Calculator { - add(a: number, b: number): number - subtract(a: number, b: number): number - divide(a: number, b: number): number - heavyOperation(...numbers: number[]): Promise - isEnabled: boolean -} - -// Create: -const calculator = Substitute.for() -``` - -Each of the following examples starts with a fresh `calculator`: - - -```typescript -// Set a return value: -calculator.add(1, 2).returns(3) - -// Use the substitute wherever a Calculator is expected (normally in the code under test): -const sum = (c: Calculator) => c.add(1, 2) -console.log(sum(calculator)) // prints 3 - -// Check received calls: -calculator.received().add(1, Arg.any()) -calculator.didNotReceive().add(2, 2) -``` - -## Creating a substitute -`Substitute.for()` creates a substitute for an interface, a class or any other type. Its type, `SubstituteOf`, is assignable to `T`, so you can hand it to the code under test. Nothing of a real instance is used: every member is substituted. (To use parts of a real instance, see [Partial mocks](#partial-mocks).) - - -```typescript -class Display { - constructor(private readonly calculator: Calculator) { } - - showSum(a: number, b: number) { - return `${a} + ${b} = ${this.calculator.add(a, b)}` - } -} - -calculator.add(1, 2).returns(3) -console.log(new Display(calculator).showSum(1, 2)) // prints 1 + 2 = 3 -``` - -A function type, or an interface with call signatures, works the same way: a call of the substitute has the setup methods, and the checks are called like the function. - -```typescript -import { Substitute, Arg, received } from '@fluffy-spoon/substitute' - -type Listener = (event: string) => string - -const listener = Substitute.for() -listener('saved').returns('ack') -listener(Arg.is(event => event.startsWith('delete'))).returns('nack') -console.log(listener('saved')) // prints ack -console.log(listener('deleted')) // prints nack - -listener.received(1)('saved') -listener[received](1)('deleted') -listener.didNotReceive()('created') -``` - -A class, or any other type that can be constructed, works the same way: `new` on a substitute, or on a member of it, is a call. It is recorded, and setups and checks written as calls apply to it: `sdk.Client(Arg.any()).returns(client)` answers `new sdk.Client('https://api')`, and `sdk.received(1).Client('https://api')` checks it. `new` returns the configured value when that is an object or a function (a setup with `throws()` throws), and otherwise the [auto-substitute](#auto-substitutes-and-nested-members) of that call, the same one that the call `sdk.Client('https://api')` returns. This holds for `new` on the substitute itself (`Substitute.for ApiClient>()`, configured as `Client('https://api').returns(client)` and checked as `Client.received(1)('https://api')`), and for `Reflect.construct()` and `new` on a function made with `bind()`, too. In TypeScript, a constructor type with several construct signatures has the call syntax for each of them. `String()` and failure messages show such a call as `new Client('https://api')`. A class can also extend a substitute; see [Classes that extend a substitute](#classes-that-extend-a-substitute). - -```typescript -import { Substitute, Arg } from '@fluffy-spoon/substitute' - -interface ApiClient { get(path: string): Promise } -interface Sdk { Client: new (baseUrl: string) => ApiClient } - -// the code under test -class UserService { - private readonly client: ApiClient - constructor(sdk: Sdk) { this.client = new sdk.Client('https://api') } - name(id: number) { return this.client.get(`/users/${id}/name`) } -} - -const sdk = Substitute.for() -const client = Substitute.for() -sdk.Client(Arg.any()).returns(client) -client.get('/users/1/name').resolves('ann') - -new UserService(sdk).name(1).then(name => console.log(name)) // prints ann -sdk.received(1).Client('https://api') -sdk.didNotReceive().Client('https://staging') - -const Client = Substitute.for ApiClient>() -Client('https://api').returns(client) -console.log(new Client('https://api') === client) // prints true -Client.received(1)('https://api') -``` - -## Setting return values -Make the call with the arguments you want to configure, then call `.returns()` on it. The same syntax works for properties. - - -```typescript -// a single value is returned by every matching call -calculator.add(1, 2).returns(4) -console.log(calculator.add(1, 2)) // prints 4 -console.log(calculator.add(1, 2)) // prints 4 - -// several values are returned in sequence, and then the last value repeats -calculator.subtract(5, 1).returns(3, 7, 9) -console.log(calculator.subtract(5, 1)) // prints 3 -console.log(calculator.subtract(5, 1)) // prints 7 -console.log(calculator.subtract(5, 1)) // prints 9 -console.log(calculator.subtract(5, 1)) // prints 9 - -// properties work the same way -calculator.isEnabled.returns(true) -console.log(calculator.isEnabled) // prints true -``` - -A call or property that is not configured does not return `undefined`: it returns an [auto-substitute](#auto-substitutes-and-nested-members). A configured value can be changed later with [`configure`](#re-configuring-a-call-configure). Another substitute is a fine return value, too. - -To make a member return `undefined`, call `.returns()` without a value. In TypeScript, that compiles whenever `undefined` is a valid value of the member: for `void`, `undefined`, `any`, `unknown` and `T | undefined`. The same goes for `.resolves()` (see [Working with promises](#working-with-promises)). Where `undefined` is not a valid value, as for a `number`, TypeScript asks for one. `.throws()`, `.rejects()` and `.mimicks()` always need an argument. - -```typescript -import { Substitute } from '@fluffy-spoon/substitute' - -interface Session { - reset(): void - currentUser(): string | undefined - timeout(): number -} - -const session = Substitute.for() -session.reset().returns() -session.currentUser().returns() -console.log(session.currentUser()) // prints undefined -// @ts-expect-error a number is needed -session.timeout().returns() -``` - -## Working with promises -For members that return a promise, `resolves()` and `rejects()` are shortcuts for returning a resolved or rejected promise. They work on methods and on promise-typed properties. They configure a native promise, so in TypeScript they are offered on every member that a native promise of the value fits: `Promise` and its subtypes without members of their own (such as Prisma's `PrismaPromise`, which only narrows `[Symbol.toStringTag]`, or subtypes whose own members are all optional), `PromiseLike`, and unions such as `void | Promise` (a hook that may be `async`), `string | Promise` or `Promise | undefined`. They take what the promise resolves to, and `resolves()` can be called without a value when `undefined` is a valid one (`Promise`, `Promise`, `Promise`, Koa's `next: () => Promise`). - - -```typescript -calculator.heavyOperation(1, 2).resolves(4) -// same as calculator.heavyOperation(1, 2).returns(Promise.resolve(4)) - -calculator.heavyOperation(0).rejects(new Error('too light')) -// like calculator.heavyOperation(0).returns(Promise.reject(new Error('too light'))), except that the -// rejected promise is only created when heavyOperation(0) is called - -async function run() { - console.log(await calculator.heavyOperation(1, 2)) // prints 4 - await calculator.heavyOperation(0).catch(error => console.log(error.message)) // prints too light -} -run() -``` - -```typescript -import { Substitute } from '@fluffy-spoon/substitute' - -interface Connection { - ready: Promise -} - -const connection = Substitute.for() -connection.ready.resolves(true) -connection.ready.then(ready => console.log(ready)) // prints true -``` - -```typescript -import { Substitute } from '@fluffy-spoon/substitute' - -interface Plugin { - onInit(): void | Promise - load(name: string): string | Promise -} - -const plugin = Substitute.for() -plugin.onInit().resolves() -plugin.load('config').resolves('{}') - -async function start(p: Plugin) { - await p.onInit() - console.log(await p.load('config')) // prints {} -} -start(plugin) -``` - -A thenable with members of its own, such as a query builder (`interface Query extends PromiseLike { where(...): Query }`), is not a promise, so `resolves()` and `rejects()` are not offered for it: a native promise has no `where()`. Neither are they for a subtype of `Promise` with members of its own, such as ky's `ResponsePromise` (`json()`, `text()`), knex's `QueryBuilder` (`where()`), execa's result (`kill()`) or a `CancellablePromise` with `cancel()`: the code under test would call these members on a native promise, which has none, and fail with "... is not a function". Configure such a member with `.returns()` and a substitute of the thenable, for code under test that calls its members: - -```typescript -import { Substitute } from '@fluffy-spoon/substitute' - -interface Row { id: number } -interface Query extends PromiseLike { - where(column: string, value: unknown): Query -} -interface Database { - query(table: string): Query -} - -// @ts-expect-error a native promise has no where() -Substitute.for().query('users').resolves([]) - -const database = Substitute.for() -const query = Substitute.for() -database.query('users').returns(query) -query.where('id', 1).returns(query) -console.log(database.query('users').where('id', 1) === query) // prints true -``` - -A substitute is never a thenable (see [Special members](#special-members)), so for code under test that `await`s such a value, return a native promise with the members added: - -```typescript -import { Substitute } from '@fluffy-spoon/substitute' - -interface CancellablePromise extends Promise { - cancel(): void -} -interface Jobs { - run(name: string): CancellablePromise -} -// a subtype without members of its own, like Prisma's -interface PrismaPromise extends Promise { - readonly [Symbol.toStringTag]: 'PrismaPromise' -} -interface Users { - count(): PrismaPromise -} - -Substitute.for().count().resolves(3) - -const jobs = Substitute.for() -// @ts-expect-error a native promise has no cancel() -jobs.run('cleanup').resolves(1) - -// the code under test awaits the result -jobs.run('backup').returns(Object.assign(Promise.resolve(1), { cancel: () => { } })) -jobs.run('backup').then(count => console.log(count)) // prints 1 - -// the code under test calls cancel() -const job = Substitute.for>() -jobs.run('report').returns(job) -jobs.run('report').cancel() -job.received(1).cancel() -``` - -## Throwing exceptions -Exceptions can be thrown from methods and properties, with different exceptions for different arguments. The exception is thrown when the configured call happens. - - -```typescript -calculator.divide(Arg.any(), 0).throws(new Error('Cannot divide by 0')) -calculator.divide(1, 0) // throws Error: Cannot divide by 0 - -calculator.isEnabled.throws(new Error('Not available')) -calculator.isEnabled // throws Error: Not available -``` - -Like `returns()`, `throws()`, `resolves()`, `rejects()` and `mimicks()` take several values, which are used in sequence. The last one repeats. - -## Mimicking an implementation -`mimicks()` runs a function of your own for the matching calls. It gets the call's arguments, and its return value is returned. - - -```typescript -calculator.add(Arg.all()).mimicks((a, b) => a + b) -console.log(calculator.add(2, 3)) // prints 5 - -let enabled = false -calculator.isEnabled.mimicks(() => enabled) -console.log(calculator.isEnabled) // prints false -enabled = true -console.log(calculator.isEnabled) // prints true -``` - -The function is called with the `this` of the call, like a method: the substitute for `calculator.add(2, 3)`, the first argument of `.call()` and `.apply()`, and `undefined` for a property read or a call through a destructured reference. If the implementation needs `this` to be something else, for example the real instance of a method you pass in, pass an arrow function or a bound method (`realCalculator.add.bind(realCalculator)`). - -`mimicks()` must be given functions. Anything else, or nothing, throws a `TypeError` right away, at the setup, and the message names the member. When the code under test calls the member with [`new`](#creating-a-substitute), the function is called with `new` if it can be: a class, an ordinary `function` or a substitute. Other functions, such as arrow functions and methods, are called as usual. - -```js -const { Substitute, Arg } = require('@fluffy-spoon/substitute') - -const repository = Substitute.for() -repository.find(Arg.any()).mimicks({ id: 1 }) // throws TypeError: mimicks() expects a function to call for @Substitute.find(Arg.any{any}), but received { id: 1 }. - -class User { - constructor(name) { this.name = name } -} -const models = Substitute.for() -models.User(Arg.any()).mimicks(User) -const ann = new models.User('ann') -console.log(ann instanceof User, ann.name) // prints true ann -``` - -## Members used as a property and as a method -A member can be configured both as a method and as a property, for example a member of a callable interface. Calls are answered by the method setups and reads by the property setup. Configure the method first. Once the property answers with a value, `stats.size(...)` is a call of that value, so configure the method through [`configure`](#re-configuring-a-call-configure) then: `stats[configure]().size(Arg.any()).returns(10)`. - -```js -const { Substitute, Arg } = require('@fluffy-spoon/substitute') - -const stats = Substitute.for() -stats.size(Arg.any()).returns(10) -stats.size.returns(3) - -console.log(stats.size('files')) // prints 10 -console.log(stats.size.toFixed(1)) // prints 3.0 -console.log(stats.size.valueOf() + 1) // prints 4 -console.log(stats.size === 3) // prints false -``` - -Because such a member must stay callable, reading it gives a function that stands in for the configured value. Reading a member of it reads that member of the value, and methods read from it run on the value, like `stats.size.toFixed(1)`. If the value is a substitute, it records and answers its own calls. The stand-in itself is not the value, so compare or compute with it through its members, for example `valueOf()`. - -## Classes that extend a substitute -The code under test can extend a substitute, or a member of one, as it would extend a base class from a library: `class Plugin extends sdk.Base { ... }`. `new Plugin(...)` is then recorded as a call `new Base(...)` of the substitute (check it with `sdk.received(1).Base(...)`), and it gives an instance of `Plugin`, with `Plugin`'s methods, as in JavaScript: - -* Without a setup, each `new Plugin()` gives a new object made from `Plugin.prototype`. -* With `sdk.Base(Arg.all()).mimicks(RealBase)`, or for `class Plugin extends Base` where `Base` is a substitute after `Base[mimick](RealBase)`, `RealBase` constructs the instance, with `Plugin` as `new.target`. -* With a setup that returns an object (`sdk.Base(Arg.any()).returns(base)`), `super()` returns that object, and so `new Plugin()` gives that object, as a base class constructor that returns an object does. - -Assignments in the constructor (`this.ready = true`) and static fields create real properties of the instance and of the class, and are not recorded. A class that extends `Base` after `Base[mimick](RealBase)` also inherits the methods of `RealBase`, because `Base.prototype` reads `RealBase.prototype`. A class that extends a member such as `sdk.Base` does not: `sdk.Base.prototype` is an [auto-substitute](#auto-substitutes-and-nested-members), whose members are auto-substitutes, too. Likewise, `Reflect.construct(sdk.Model, [1], Other)` gives an instance of `Other`, and a function made with `bind()` from a class (`Connection.bind(null, 'db')`) can be given to `mimicks()` and `[mimick]()`: `new` constructs it. A class that extends a substitute has the `call`, `apply` and `bind` of every function (`Plugin.bind === Function.prototype.bind`), so `new (Plugin.bind(null, 'audit'))()` constructs a `Plugin`, which is recorded as `new Base('audit')`, and `Plugin.call(null, 'audit')` throws the `TypeError` of calling a class without `new`, as in JavaScript. Reading them records nothing. Only when the substitute configures a member of that name (`sdk.Base[configure]().bind(Arg.all()).returns(value)`), or mimicks an instance that has one of its own, does that setup or instance answer instead. - -```js -const { Substitute, Arg } = require('@fluffy-spoon/substitute') - -class RealBase { - constructor(name) { this.name = name } -} - -// the code under test extends a base class of an SDK -const definePlugin = sdk => class Plugin extends sdk.Base { - constructor(name) { - super(name) - this.ready = true - } - describe() { return `plugin ${this.name}` } -} - -const sdk = Substitute.for() -sdk.Base(Arg.all()).mimicks(RealBase) -const Plugin = definePlugin(sdk) - -const plugin = new Plugin('audit') -console.log(plugin instanceof Plugin, plugin.ready, plugin.describe()) // prints true true plugin audit -sdk.received(1).Base('audit') - -// a constructor bound with the class' own bind(), as a registry of plugins makes them -const AuditPlugin = Plugin.bind(null, 'audit') -console.log(new AuditPlugin().describe()) // prints plugin audit -sdk.received(2).Base('audit') - -// the code under test hands the instance to another substitute -const host = Substitute.for() -host.register(plugin) -host.received(1).register(plugin) -host.received(1).register(Arg.any('object')) -console.log(JSON.stringify(plugin)) // prints {"name":"audit","ready":true} -console.log(plugin) // prints Plugin { name: 'audit', ready: true } -// a symbol that is not registered with Symbol.for() reads as undefined through the instance -console.log(plugin[Symbol('internal')]) // prints undefined - -// without a setup, every `new` gives a new instance -const Unconfigured = definePlugin(Substitute.for()) -console.log(new Unconfigured('a') !== new Unconfigured('a'), new Unconfigured('b') instanceof Unconfigured) // prints true true -``` - -Instances of such a class, and any other object whose prototype chain leads to a substitute (`Object.create(sub)`, or objects made from such instances), are ordinary objects, to the library and to the code that looks at them: - -* Passed to a substitute, they are recorded, checked and matched like other objects: by [deep strict equality](#how-arguments-are-compared) of their own fields and their prototype, and `Arg.any('object')` matches them. -* `JSON.stringify(plugin)` gives their own fields. `util.inspect()`, `console.log()`, failure messages, and the messages and snapshots of jest and vitest show them with their class, as `Plugin { name: 'audit', ready: true }`. `String(plugin)`, template strings and `plugin + ''` give `[object Object]`, as with an empty base class. -* Through such an object, the substitute answers `then`, `toJSON`, `Symbol.toPrimitive`, `util.inspect.custom`, the library's own symbols and every other symbol that is not registered with `Symbol.for()` (such as `Symbol('id')`, or the private symbols that Node.js' own checks look for) with `undefined`, without recording these reads, and `toString` and `valueOf` with those of `Object.prototype` (with `Function.prototype.toString` for the class itself), unless the substitute configures or mimicks them. -* A class that extends a substitute is not a substitute itself: `Arg.any('object')` does not match it (`Arg.any('function')` does), and it has no `[received]()`. - -Other members that neither the instance nor its class has, symbols registered with `Symbol.for()` among them, are still read from the `prototype` of the substitute, which is an auto-substitute, and these reads are recorded there. The library itself reads nothing from the substitute through such an object, when it compares it with the arguments of setups and checks or prints it, also when the substitute belongs to another copy of the package than the one that compares or prints (see [The symbol API](#the-symbol-api)). Other code may: `util.inspect()` on Node.js 20.20 and newer reads `href` of every object it prints, so calling it on such an instance, in the test or in the code under test, records a read of `Base.prototype.href` on `sdk`, and on Node.js 20.20, `util.isDeepStrictEqual()` called by your own code on such instances reads their `href`, `protocol` and `auth`, recorded as `Base.prototype.href` and so on (on Node.js 18, 22 and newer, it reads nothing there). On Node.js 20 only, `String(plugin)` is `[object Function]`: V8 there takes every object whose prototype is a proxy of a function for a function, with or without the library. - -# Argument matchers -There are several ways of matching arguments. They work the same when you set up calls and when you verify them, and they also work for property assignments (`calculator.received().isEnabled = Arg.any()`). - -## Matching specific arguments -`Arg.any()` matches any value. `Arg.is(predicate)` matches the values for which the predicate returns a truthy value (`Arg.is(user => user.name)` matches `{ name: 'ann' }`). When `Arg.is` replaces an argument, the type of the predicate's parameter is inferred from that argument. That holds for generic methods, too, with the method's type parameters replaced by their constraints, also when they appear only in the return type, as in a database client's `query(sql: string): Promise` (see the second example). It does not hold for a rest parameter whose type depends on a type parameter, such as the event arguments of a typed event emitter's `emit(event: E, ...args: Parameters)` or of Node.js' `EventEmitter`: there, a predicate without a parameter type gets the parameter types of all events together, or `unknown` with Node.js' `EventEmitter`, and the call does not compile. (With `@types/node` 25 and newer, it gets `any` on `EventEmitter`, so nothing checks it.) Annotate the parameter there: `emitter.emit('saved', Arg.is((id: string) => id.startsWith('o')))` (see [Typing limitations](#typing-limitations)). - - -```typescript -// ignoring the first argument -calculator.add(Arg.any(), 2).returns(10) -console.log(calculator.add(1337, 2)) // prints 10 -// calculator.add(1337, 3) does not match: it returns an auto-substitute, not 10 - -// x is inferred as a number -calculator.subtract(Arg.is(x => x < 0), Arg.any()).returns(0) -console.log(calculator.subtract(-5, 3)) // prints 0 - -// matchers verify received calls, too -calculator.received().add(Arg.is(x => x > 1000), 2) -``` - -```typescript -import { Substitute, Arg, configure } from '@fluffy-spoon/substitute' - -interface Database { - query(sql: string, params?: readonly unknown[]): Promise -} -interface Cache { - get: (key: string) => Promise -} - -const database = Substitute.for() -// sql is inferred as a string -database.query(Arg.is(sql => sql.startsWith('SELECT'))).resolves([]) -database[configure]().query('DELETE FROM users', Arg.is(params => params !== undefined && params.length === 1)).resolves([]) -database.query('SELECT 1').then(rows => console.log(rows)) // prints [] -database.received(1).query(Arg.is(sql => sql.startsWith('SELECT'))) - -const cache = Substitute.for() -cache.get(Arg.is(key => key.startsWith('user:'))).resolves(undefined) -``` - -Outside of an argument position, for example in a variable, there is nothing to infer the type from, so annotate the parameter: - - -```typescript -const negative = Arg.is((x: number) => x < 0) -calculator.divide(negative, negative).returns(1) -console.log(calculator.divide(-4, -2)) // prints 1 -``` - -In TypeScript, too, a predicate can return any value that is not a promise, and its truthiness decides: `Arg.is(user => user.name)` (a `string | undefined`), `Arg.is(user => user.roles.length)` (a `number`) and `Arg.is(user => user.name?.startsWith('a'))` (a `boolean | undefined`) compile, and a type guard such as `Arg.is(isHttpError)` fits as well. A predicate that returns a promise or another thenable, such as an `async` one (see below), does not compile, and neither does one declared to return `unknown`. For a parameter of a specific type (`save(user: User)`, `byName(name: string)`, also an optional `v?: User`, and in checks such as `repo.received(1).save(Arg.is(Boolean))`), `Arg.is(Boolean)` does not compile on TypeScript 3.8 and newer (TS2769, "No overload matches this call"). It compiles for parameters typed `unknown`, `any` or `object`, on its own (`const isSet = Arg.is(Boolean)`), and on TypeScript 3.6 and 3.7. Write `Arg.is(value => Boolean(value))`, which compiles everywhere. On TypeScript 7, a predicate with a block body that returns nothing (`Arg.is(user => { user.name })`) compiles; it never matches. - - -```typescript -interface User { name?: string; roles: string[] } -interface Repository { save(user: User): string } - -const repository = Substitute.for() -repository.save(Arg.is(user => user.roles.length)).returns('with roles') -repository.save(Arg.is(user => user.name)).returns('named') -console.log(repository.save({ name: 'ann', roles: [] })) // prints named -console.log(repository.save({ roles: ['admin'] })) // prints with roles -repository.received(1).save(Arg.is(user => user.name?.startsWith('a'))) -repository.received(2).save(Arg.is(user => Boolean(user))) - -// @ts-expect-error a predicate must not return a promise -repository.save(Arg.is(async user => user.name === 'ann')).returns('async') -// @ts-expect-error Arg.is(Boolean) does not fit a parameter of a specific type -repository.received(2).save(Arg.is(Boolean)) -``` - -`Arg.is()` with something other than a function throws a `TypeError` right away. A predicate that throws, for example because it reads a property of `null`, counts as a non-match: the code under test is not affected, and a failed assertion says that the predicate threw. - -A predicate can look at a substitute that the code under test passed, and nothing that it does there leaves a trace. Its reads and calls are not recorded, so later checks and printouts do not see them, and they do not use up the values of a `returns()`, `resolves()`, `rejects()` or `throws()` sequence: the predicate sees the value that the next read or call of the code under test gets. Its assignments are not made, not even on a mimicked instance. Setups still answer it, and mimicked instances and `mimicks()` functions still run (their own calls of substitutes leave no trace either). A `throws()` setup throws inside the predicate, which then counts as a non-match, and a promise of `rejects()` that the predicate sees is marked as handled. This holds for the [matchers of test runners](#matchers-of-test-runners) as well. How far it reaches depends on where the predicate runs: - -* In a check (`received()`, `didNotReceive()`), nothing that the predicate does while it runs leaves a trace, on any substitute: also what a callback that it calls does, and what it does to a substitute that it creates itself (a check that the predicate makes on such a substitute finds nothing). An `async` callback runs only up to its first `await` while the predicate runs, though: what it does after that runs later, and is recorded like any call of the code under test. So with a callback such as the one of TypeORM's `dataSource.transaction(async manager => { ... })`, Prisma's `$transaction()` or a retry wrapper, what a check's predicate leaves behind depends on where the callback awaits. Run such callbacks with a `mimicks()` function of the setup instead (see below). -* When a call of the code under test is compared with the setups, only the predicate's look at the values being compared leaves no trace: the substitutes among the call's arguments, also inside arrays, `Map`s, `Set`s, the own enumerable properties of objects (not behind getters) and the prototype chain of an object (such as an instance of `class Job extends queue.Job`), and what those substitutes answer, in turn. The library looks for them when the predicate first uses a substitute, in the arguments as they are at that moment, however many items, keys or entries they have, up to 32 levels deep and 8 steps up a prototype chain. Everything else is recorded and uses up the values of sequences, as any other call: what the code under test does in a callback that the predicate calls (`Arg.is(callback => { callback(null, rows); return true })`), a substitute that the predicate reads without its being among the arguments, such as one that it closes over, and a substitute that it creates itself (a check that the predicate makes on it finds what it did). - -A setup or a check that the predicate writes with matchers works as it does elsewhere. - -```js -const { Substitute, Arg } = require('@fluffy-spoon/substitute') - -const user = Substitute.for() -user.name.returns('ann', 'bob') -const bus = Substitute.for() -// the code under test publishes the user -bus.publish(user) - -bus.received(1).publish(Arg.is(u => u.name === 'ann')) -// the predicate's read is not recorded, and it did not use up 'ann' -user.didNotReceive().name -console.log(user.name) // prints ann - -// the same when a call of the code under test is compared with a setup -const repository = Substitute.for() -repository.save(Arg.is(u => u.name === 'bob')).returns('saved') -console.log(repository.save(user)) // prints saved -user.received(1).name -``` - -A predicate runs each time a value is compared with it: when a call of the code under test is compared with the setups, once for each setup with a predicate that the call is compared with (the newest first, until one matches), and in a check, once for each received call that the check compares. So a callback that a predicate calls runs several times, and in checks, what it does is not recorded. To make a substitute call a callback that the code under test passes, give the setup a `mimicks()` function, which runs once for each call that the setup answers: - -```js -const { Substitute, Arg } = require('@fluffy-spoon/substitute') - -// the code under test runs a query, and logs the number of rows in its callback -const countRows = (db, logger) => db.query('SELECT id FROM users', (error, rows) => logger.info('rows', rows.length)) - -const db = Substitute.for() -const logger = Substitute.for() -db.query(Arg.any(), Arg.any()).mimicks((sql, callback) => callback(null, [{ id: 7 }])) -countRows(db, logger) -logger.received(1).info('rows', 1) - -// a predicate that calls the callback: what the callback does when a call is compared with the setup is recorded -const db2 = Substitute.for() -const logger2 = Substitute.for() -db2.query(Arg.any(), Arg.is(callback => { callback(null, [{ id: 7 }]); return true })).returns() -countRows(db2, logger2) -logger2.received(1).info('rows', 1) -// a check runs the predicate again, and what the callback does there is not recorded -db2.received(1).query(Arg.any(), Arg.is(callback => { callback(null, []); return true })) -logger2.didNotReceive().info('rows', 0) -``` - -A `mimicks()` function drives an `async` callback as well, all of it: - -```js -const { Substitute, Arg } = require('@fluffy-spoon/substitute') - -// the code under test saves in a transaction -const saveNew = (dataSource, names) => dataSource.transaction(async manager => { - const existing = await manager.find('users') - manager.save(names.filter(name => !existing.includes(name))) -}) - -const dataSource = Substitute.for() -const manager = Substitute.for() -manager.find(Arg.any()).resolves(['bob']) -dataSource.transaction(Arg.any()).mimicks(work => work(manager)) - -saveNew(dataSource, ['ann', 'bob']).then(() => { - manager.received(1).save(['ann']) - console.log('saved') // prints saved -}) -``` - -A predicate must decide synchronously. One that returns a promise or another thenable, such as an `async` function, throws a `TypeError` where it is used: in the check, or in the call of the code under test that a setup with it is compared with, also inside an object or an array (`repo.save({ id: Arg.is(async id => ...) })`). (In TypeScript, it does not compile.) Its promise is handled, so no unhandled rejection follows. Await what the predicate needs before the setup or the check: - -```js -const { Substitute, Arg } = require('@fluffy-spoon/substitute') - -const repository = Substitute.for() -repository.save({ name: 'ann' }) -repository.received(1).save(Arg.is(user => user.name)) // a truthy value matches -repository.received(1).save(Arg.is(async user => user.name === 'ann')) // throws TypeError: Arg.is{async user => user.name === 'ann'} returned a promise (or another thenable), but an Arg.is predicate must return whether the value matches synchronously -repository.received(1).save({ name: Arg.is(async name => name === 'ann') }) // throws TypeError: returned a promise (or another thenable) -``` - -The matchers must be called. In JavaScript, a matcher function passed as it is, such as `Arg.any` instead of `Arg.any()`, would only match that function itself, so a setup with it would never answer and a `didNotReceive()` check with it would always pass. As a direct argument of a setup or a check, `Arg.any`, `Arg.any.not`, `Arg.is`, `Arg.is.not` and `Arg.all` therefore throw a `SubstituteException` that suggests the call. (TypeScript rejects them, unless the parameter takes functions, `any` or `unknown`.) Inside an object or array, they are compared as values, and the code under test can pass them in its own calls, which are recorded as usual. - -```js -const { Substitute, Arg } = require('@fluffy-spoon/substitute') - -const repository = Substitute.for() -repository.find(Arg.any).returns('ann') // throws SubstituteException: 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()? -repository.didNotReceive().delete(Arg.is) // throws SubstituteException: Did you mean Arg.is(predicate)? -``` - -## Matching by type -`Arg.any(type)` matches values of a type: - -| `type` | Matches | -|---|---| -| `'any'` (the default) | any value, including `undefined` and `null` | -| `'string'`, `'number'`, `'boolean'`, `'symbol'`, `'bigint'`, `'undefined'` | values with that `typeof` | -| `'object'` | objects, arrays and substitutes, but not `null` | -| `'function'` | functions (and classes) and substitutes | -| `'array'` | arrays (`Array.isArray`) | - -```typescript -import { Substitute, Arg } from '@fluffy-spoon/substitute' - -interface Printer { - print(value: unknown): string -} - -const printer = Substitute.for() -printer.print(Arg.any('string')).returns('a string') -printer.print(Arg.any('object')).returns('an object') -printer.print(Arg.any('array')).returns('an array') - -console.log(printer.print('hello')) // prints a string -console.log(printer.print({ id: 1 })) // prints an object -// an array matches both 'object' and 'array'; the setup made last wins (see "Match order") -console.log(printer.print([1, 2])) // prints an array - -printer.print(null) -// { id: 1 } and [1, 2] are objects, null is not -printer.received(2).print(Arg.any('object')) -``` - -Any other type name, for example a typo or another case such as `'String'`, throws a `TypeError` right away, in `Arg.any()` and in `Arg.any.not()` (TypeScript does not compile it in the first place): `Arg.any expects one of 'any', 'string', 'number', 'boolean', 'symbol', 'undefined', 'object', 'function', 'array', 'bigint' (or no argument for 'any'), but received 'strnig'.` - -```js -const { Substitute, Arg } = require('@fluffy-spoon/substitute') - -const printer = Substitute.for() -printer.print(Arg.any('bigint')).returns('a bigint') -console.log(printer.print(10n)) // prints a bigint - -Arg.any.not('strnig') // throws TypeError: Arg.any.not expects one of -``` - -In TypeScript, a type matcher must fit the parameter. `Arg.any('string')` is typed `string`, `Arg.any('number')` `number`, and so on for `'boolean'`, `'symbol'` and `'bigint'`, wherever the matcher is written. So it fits a parameter that accepts every value of its type, and an overloaded method takes the overload that a `string` (or `number`, ...) would take: `stream.on(Arg.any('string'), Arg.any())`, `document.querySelector(Arg.any('string'))`, and `get(Arg.any('string'))` for a getter that declares `get(key: 'retries'): number` before `get(key: string): string | undefined` have the setup API of the overload for any string. A type matcher does not fit a parameter that takes only some values of its type: a union of string literals (`'EUR' | 'USD'`), a string enum, a branded string (`string & { __brand: 'OrderId' }`), a union of number literals (`80 | 443`), a branded number, or `true`. TypeScript reports, for example, `Argument of type 'ReturnArg' is not assignable to parameter of type 'Currency'`. (A numeric enum accepts `Arg.any('number')`, as it accepts any number.) There, give an `Arg.is()` predicate the parameter's type, `Arg.is((currency: Currency) => true)`, which matches every value, or cast the type matcher, `Arg.any('string') as Currency`, which still matches every string; a branded type needs the cast through `unknown` (`Arg.any('string') as unknown as OrderId`), as TypeScript rejects `Arg.any('string') as OrderId`. Nor does a type matcher fit a parameter that takes no value of its type, such as `Arg.any('string')` for a number. `Arg.any('undefined')` only fits a parameter that accepts `undefined`, such as `string | undefined`, an optional parameter or `unknown`. `Arg.any()` and `Arg.any('object')` fit any parameter (see [Typing limitations](#typing-limitations)). `Arg.any('undefined')` also matches an argument that the call leaves out (see [How arguments are compared](#how-arguments-are-compared)). - -```typescript -import { Substitute, Arg } from '@fluffy-spoon/substitute' - -interface Users { - find(name?: string): string - count(limit: number): number -} - -const users = Substitute.for() -users.find(Arg.any('undefined')).returns('all users') -console.log(users.find(undefined)) // prints all users -console.log(users.find()) // prints all users - -// @ts-expect-error a number parameter does not accept undefined -users.count(Arg.any('undefined')) -``` - -```typescript -import { Substitute, Arg } from '@fluffy-spoon/substitute' - -type Currency = 'EUR' | 'USD' -enum Status { Open = 'open', Paid = 'paid' } -enum Priority { Low, High } -type OrderId = string & { readonly __brand: 'OrderId' } - -interface Payments { - charge(currency: Currency, cents: number): string - setStatus(id: OrderId, status: Status): void - setPriority(id: OrderId, priority: Priority): void -} - -const payments = Substitute.for() -payments.charge(Arg.is((currency: Currency) => true), Arg.any('number')).returns('charged') -payments.setStatus(Arg.is((id: OrderId) => true), Arg.any('string') as Status).returns() -// a numeric enum accepts Arg.any('number') -payments.setPriority(Arg.any('string') as unknown as OrderId, Arg.any('number')).returns() -console.log(payments.charge('EUR', 100)) // prints charged -payments.received(1).charge(Arg.any('string') as Currency, 100) - -// @ts-expect-error Arg.any('string') is typed string, which is not a Currency -payments.charge(Arg.any('string'), 100) -// @ts-expect-error a string matcher does not fit a number parameter -payments.charge('EUR', Arg.any('string')) -// @ts-expect-error a branded type needs the cast through unknown -payments.setPriority(Arg.any('string') as OrderId, Priority.High) - -// overloads: Arg.any('string') takes the overload for any string -interface Settings { - get(key: 'retries'): number - get(key: string): string | undefined -} -const settings = Substitute.for() -settings.get(Arg.any('string')).returns('dark') -console.log(settings.get('theme')) // prints dark -``` - -The encoding of Node.js' `fs.readFile(path, options)` is such a parameter: every overload types it as a union of string literals (`BufferEncoding`) or an options object, so `fs.readFile(Arg.any(), Arg.any('string'))` does not compile, in a setup or in a check. Pass the encoding itself, cast the matcher to `BufferEncoding`, or give an `Arg.is()` predicate that type. A check can also take `Arg.any()` for it. In a setup, `fs.readFile(Arg.any(), Arg.any())` takes the first overload, which gives a `Buffer`, so `.resolves()` does not take a string there: use the encoding or the cast for a string result. `fs.readFile(Arg.all())`, which answers the calls of every overload, takes a string or a `Buffer` (see [Ignoring all arguments](#ignoring-all-arguments)). - -```typescript -import { Substitute, Arg } from '@fluffy-spoon/substitute' - -const fs = Substitute.for>() -fs.readFile('config.json', 'utf8').resolves('{}') -fs.readFile(Arg.any(), Arg.any('string') as BufferEncoding).resolves('') -fs.readFile(Arg.any(), Arg.any()).resolves(Buffer.from('binary')) -// Arg.all() alone takes what any overload resolves to -fs.readFile(Arg.all()).resolves('text') - -// @ts-expect-error every overload types the encoding as a union of string literals -fs.readFile(Arg.any(), Arg.any('string')).resolves('') -// @ts-expect-error Arg.any() for the options takes the first overload, which gives a Buffer -fs.readFile(Arg.any(), Arg.any()).resolves('') - -// the code under test -fs.readFile('config.json', 'utf8').then(text => console.log(text)) // prints {} -fs.received(1).readFile('config.json', Arg.is((encoding: BufferEncoding) => encoding === 'utf8')) -fs.received(1).readFile(Arg.any(), Arg.any()) -``` - -## Inverse matchers -`Arg.is.not(predicate)` and `Arg.any.not(type)` match the values that the matcher without `.not` does not match. - - -```typescript -const isZero = (x: number) => x === 0 - -// the first argument matches any number, the second any number except 0 -calculator.divide(Arg.any('number'), Arg.is.not(isZero)).returns(10) -console.log(calculator.divide(100, 10)) // prints 10 -// calculator.divide(100, 0) does not match - -calculator.received(1).divide(Arg.any(), Arg.is.not(isZero)) -calculator.didNotReceive().divide(Arg.any.not('number'), Arg.any()) -``` - -## Ignoring all arguments -`Arg.all()` as the only argument matches every call, whatever its arguments: - - -```typescript -calculator.add(Arg.all()).returns(10) -console.log(calculator.add(1, 3)) // prints 10 -console.log(calculator.add(5, 2)) // prints 10 -``` - -After other arguments, `Arg.all()` matches the rest of the arguments, which can also be none. The arguments before it must match as usual. Arguments after `Arg.all()` are an error (a `SubstituteException`). - -```typescript -import { Substitute, Arg } from '@fluffy-spoon/substitute' - -interface Logger { - log(message: string, ...details: string[]): void -} - -const logger = Substitute.for() -logger.log('saved') -logger.log('saved', 'id 42', 'extra') -logger.log('deleted', 'id 7') - -logger.received(2).log('saved', Arg.all()) -logger.received(1).log('deleted', Arg.all()) -logger.received(3).log(Arg.all()) -``` - -On an overloaded method, `Arg.all()` alone answers the calls of every overload, so in TypeScript it takes the value of any of them: `.returns()` takes what any overload returns, `.resolves()` and `.rejects()` what any of their promises resolve to, and `.mimicks()` a function that fits each overload, as a function assigned to the method does, and returns what any overload returns. So `pool.query(Arg.all()).resolves(result)` compiles with `@types/pg`, whose first overload of `query()` returns a stream. The `mimicks()` function may leave out trailing parameters that the overloads pass (`(text: string) => ...` for `query(text, values?)` and `query(text, callback)`, `(entity: any) => ...`, `async path => ...`), and an untyped parameter gets the parameter types of all the overloads at its position, on every supported TypeScript version (plain TypeScript types the parameters of a function assigned to an overloaded method only from 4.3 on). A `mimicks()` function does not compile when one of its parameters does not take what some overload passes there: for `get(): string[]` and `get(key: string): string`, `store.get(Arg.all()).mimicks((key: string) => key)` does not, and neither do `(key: any) => key` and the untyped `key => 'a'`, because `get()` passes no key. Make such parameters optional (`(key?: string) => ...`), or take `(...args: any[])`. For `query(text, values?)` and `query(text, callback)`, `(text: string, values?: unknown[]) => ...` does not compile either, because the second overload passes a function there (TypeScript rejects that function for the method, too). Nor does a function with a parameter that no overload passes, or one that returns what no overload returns. A union of functions, such as `cond ? takesEveryCall : takesAnyRow` or a value typed as a union, fits only when each of them does, as for the method itself: when one of them does not fit, TypeScript rejects it with TS2345 and names the type `{ readonly '@fluffy-spoon/substitute:every-implementation-must-fit': ... }` in the parameter's type. This holds in the `configure` view, for `[mimicks]` and for the later functions of a sequence as well, and an overloaded function that fits each overload, such as the method of a real instance (`repo.remove(Arg.all()).mimicks(realRepository.remove)`), compiles. 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 (see [Typing limitations](#typing-limitations), 'Generic methods'). Only the last 8 overloads count (see [Typing limitations](#typing-limitations)). When all the overloads that count return the same type, nothing of this changes: `.mimicks()` takes a function with the parameters of the first of them. fastify's `addHook` overloads, for example, all return the instance, so `app.addHook(Arg.all()).mimicks(...)` takes the parameters of the first overload that counts (`'onRoute'`): `(name, hook) => app` compiles, but a function annotated for another hook, such as `(name: 'onRequest', hook: onRequestHookHandler) => app`, does not. Use `(...args: any[]) => app` or `(name: string, hook: Function) => app` there. A setup with other arguments before `Arg.all()` (`pool.query(Arg.any('string'), Arg.all())`), and one with `Arg.any()` for each argument, take the first overload that accepts their arguments, as a call does, except on overloads that are generic with constrained type parameters: where an argument's type is the type parameter itself, as in TypeORM's `save(entity: T)`, `Arg.any()` gets the method's own overload and no setup API, and where it only contains the type parameters, as in AWS SDK v3's `send(command)`, a concrete command, a typed `Arg.is()` predicate or a cast does (see [Typing limitations](#typing-limitations), 'Overloads that are generic with constrained type parameters'). - -```typescript -import { Substitute, Arg } from '@fluffy-spoon/substitute' - -// the overloads of @types/pg's Pool.query, in short -interface Submittable { submit(connection: unknown): void } -interface QueryResult { rows: unknown[] } -interface Pool { - query(queryStream: T): T - query(text: string, values?: unknown[]): Promise - query(text: string, callback: (error: Error, result: QueryResult) => void): void -} - -const pool = Substitute.for() -pool.query(Arg.all()).resolves({ rows: [{ id: 1 }] }) -pool.query('SELECT * FROM users').then(result => console.log(result.rows)) // prints [ { id: 1 } ] -// @ts-expect-error no overload resolves to a number -pool.query(Arg.all()).resolves(42) - -// a mimicks() function takes the arguments of every overload -pool.query(Arg.all()).mimicks((...args: any[]) => Promise.resolve({ rows: [] })) -// @ts-expect-error the stream overload passes a Submittable, not a string -pool.query(Arg.all()).mimicks((text: string) => Promise.resolve({ rows: [] })) - -interface Store { get(): string[]; get(key: string): string } -const store = Substitute.for() -store.get(Arg.all()).mimicks((key?: string) => key === undefined ? ['a', 'b'] : key) -console.log(store.get(), store.get('a')) // prints [ 'a', 'b' ] a -// @ts-expect-error get() passes no key -store.get(Arg.all()).mimicks((key: string) => key) -// @ts-expect-error get() passes no key, so the parameter must be optional -store.get(Arg.all()).mimicks(key => 'a') -``` - -```typescript -import { Substitute, Arg } from '@fluffy-spoon/substitute' - -// the overloads of @types/pg's Client.query that take text, in short -interface QueryResult { rows: unknown[] } -interface Client { - query(text: string, values?: unknown[]): Promise - query(text: string, callback: (error: Error | undefined, result: QueryResult) => void): void -} - -const client = Substitute.for() -// a mimicks() function may leave out parameters, as a function assigned to the method may -client.query(Arg.all()).mimicks((text: string) => Promise.resolve({ rows: [text] })) -// an untyped parameter takes the parameter types of all the overloads at its position -client.query(Arg.all()).mimicks(text => Promise.resolve({ rows: [text.toUpperCase()] })) -client.query('select 1').then(result => console.log(result.rows)) // prints [ 'SELECT 1' ] -// @ts-expect-error the callback overload passes a function, not values -client.query(Arg.all()).mimicks((text: string, values?: unknown[]) => Promise.resolve({ rows: [] })) - -interface Row { id: number } -interface Rows { - remove(rows: Row[], options?: { chunk?: number }): Promise - remove(row: Row, options?: { chunk?: number }): Promise -} -const rows = Substitute.for() -rows.remove(Arg.all()).mimicks((row: any) => Promise.resolve(row)) -// row is a Row[] | Row -rows.remove(Arg.all()).mimicks(row => Promise.resolve(row as any)) -rows.remove({ id: 7 }).then(removed => console.log(removed)) // prints { id: 7 } -// @ts-expect-error the first overload passes a Row[] -rows.remove(Arg.all()).mimicks((row: Row) => Promise.resolve(row)) -// @ts-expect-error no overload passes a third argument -rows.remove(Arg.all()).mimicks((row: any, options: any, extra: any) => Promise.resolve(row)) - -// a union of functions fits when each of them does -const everyCall = (...args: any[]) => Promise.resolve(args[0]) -const anyRow = (row: any) => Promise.resolve(row) -const oneRow = (row: Row) => Promise.resolve(row) -const all = rows !== undefined -rows.remove(Arg.all()).mimicks(all ? everyCall : anyRow) -// @ts-expect-error oneRow does not take the Row[] that the first overload passes -rows.remove(Arg.all()).mimicks(all ? everyCall : oneRow) -``` - -`Arg.any()` stands for one argument, and `Arg.all()` for any arguments. TypeScript accepts a lone `Arg.any()` for a method with more parameters, because `Arg.any()` is typed `any` and so also fits the signature that takes `Arg.all()`. But such a setup or check only matches calls with one argument (the other positions count as `undefined`, see [How arguments are compared](#how-arguments-are-compared)): after `calculator.add(1, 2)`, `calculator.didNotReceive().add(Arg.any())` passes, and `calculator.add(Arg.any()).returns(3)` does not answer `calculator.add(1, 2)`. Write `add(Arg.all())`, or `add(Arg.any(), Arg.any())`. Typed matchers, such as `Arg.any('number')` and `Arg.is((x: number) => x > 0)`, are checked against the number of parameters. - - -```typescript -calculator.add(1, 2) - -// a lone Arg.any() only matches calls with one argument -calculator.didNotReceive().add(Arg.any()) -calculator.received(1).add(Arg.all()) -calculator.received(1).add(Arg.any(), Arg.any()) -// @ts-expect-error add() takes two arguments -calculator.didNotReceive().add(Arg.any('number')) -``` - -## Matchers inside objects and arrays -Matchers also work inside plain objects and arrays, also nested ones (up to the limits below). An object with a matcher matches an argument with the same keys (in any order), and an array with a matcher matches an array of the same length. Each nested matcher matches by its own rule, and every other value must be [equal](#how-arguments-are-compared). Like any call with a matcher, such a call is a setup or a check, never a received call, and in the [match order](#match-order) it ranks with the other matcher setups. - -```typescript -import { Substitute, Arg } from '@fluffy-spoon/substitute' - -interface User { - id: number - name: string - roles: string[] -} - -interface Repository { - save(user: User): string -} - -const repository = Substitute.for() -repository.save({ id: Arg.any(), name: 'bob', roles: [Arg.is(role => role.startsWith('admin'))] }).returns('saved') - -console.log(repository.save({ id: 1, name: 'bob', roles: ['admin:all'] })) // prints saved -console.log(repository.save({ name: 'bob', roles: ['admin:read'], id: 2 })) // prints saved -// another name, or a second role, does not match -repository.save({ id: 3, name: 'ann', roles: ['admin:all'] }) -repository.save({ id: 4, name: 'bob', roles: ['admin:all', 'user'] }) - -repository.received(2).save({ id: Arg.any(), name: 'bob', roles: [Arg.any()] }) -repository.received(4).save(Arg.all()) -repository.didNotReceive().save({ id: Arg.any(), name: 'bob', roles: [] }) -``` - -* `Arg.all()` as the last item of an array matches the remaining items, also none: `['level', Arg.all()]` matches `['level']` and `['level', 1, 2]`. Anywhere else in an array it is a `SubstituteException`. As the value of a key, `Arg.all()` matches any value, but the key must be there. (In TypeScript, `Arg.all()` inside an object or array does not type-check; use `Arg.any()` for a single value.) -* Only plain objects (created with `{ }` or `Object.create(null)`) and arrays are searched for matchers, and an object with matchers only matches an argument with the same prototype: `{ id: Arg.any() }` does not match a class instance. A matcher inside a class instance, a `Map` or a `Set` is not looked for: it is compared as a value, so such a setup never matches, and the call is an ordinary call. Matchers behind getters are not looked for either. Use `Arg.is()` for the whole argument in these cases. -* An array that holds a matcher is compared by its items only. Its other keys, such as the `total` of an array of rows, are not compared then: `Object.assign([Arg.any(), 2], { total: 5 })` matches `[1, 2]` and `Object.assign([1, 2], { total: 9 })`, too. An array without a matcher is compared in full, other keys included. Use `Arg.is()` for the whole array to check its other keys along with a matcher. -* Each argument is searched for a matcher 32 levels deep: arrays and objects more than 32 levels below the argument are not searched. When that finds no matcher, a matcher further down is not found: it is compared as a value, as above, and unless another argument has a matcher, the call is an ordinary call. When it finds one, every array and plain object of that argument is searched, at any depth, so a matcher further down in it is used as well: in `{ id: Arg.any(), tree }`, the matchers deep in `tree` count too. The arrays and plain objects are searched whatever their size, each time the argument is passed, and one that several values of one argument refer to, or that refers to itself, is searched once. -* `String(sub)` shows nested matchers, for example `save({ id: Arg.any{any}, name: 'bob' }) => returns('saved')`. - -## Matchers of test runners -The asymmetric matchers of jest and vitest work as argument matchers, in setups and in checks: `expect.any()`, `expect.anything()`, `expect.stringContaining()`, `expect.stringMatching()`, `expect.objectContaining()`, `expect.arrayContaining()`, `expect.closeTo()`, their `expect.not` forms, and the matchers that `expect.extend()` adds. So do sinon's matchers: `sinon.match(...)`, `sinon.match.has('err')`, `sinon.match.string` and the others. A jest or vitest matcher matches a value when its `asymmetricMatch(value)` returns a truthy value, and a sinon matcher when its `test(value)` does. They work at the top level and inside plain objects and arrays, within the limits of [matchers inside objects and arrays](#matchers-inside-objects-and-arrays), and otherwise behave like `Arg` matchers, too: - -* A call with one is a setup or a check, never a received call, and it runs no setup (see [What counts as a call](#what-counts-as-a-call)). -* In the [match order](#match-order), a setup with one ranks with the other matcher setups. A setup with an equal matcher (`expect.any(String)` again) replaces it. -* Inside a class instance, a `Map` or a `Set`, such a matcher is a value, and so is one that the code under test assigns to a property: `form.email = expect.any(String)` is recorded with that object as the value. -* A matcher that throws counts as a non-match. The failure message says so in the words it uses for `Arg.is()`: `(an Arg.is predicate threw while matching this call: ...)`. -* Failure messages and printouts show them as the runner does, such as `Any`, `Anything`, `StringContaining '@'`, `StringNotContaining 'x'`, `ObjectContaining { customer: 'cus_1' }`, `ArrayContaining [ 'vip' ]` and `NumberCloseTo 0.3 (5 digits)`, and sinon's by their message, such as `has("err")` or `typeOf("string")`. Matchers inside the sample of another one print the same way, at any depth: `send(ObjectContaining { input: ObjectContaining { items: ArrayContaining [ 3 ] } })`, also in printouts and paths. The sample is part of the matcher's text: where the matcher is deeper than the printed depth, its sample still shows its first level, the objects and arrays inside it that hold a matcher show at any depth, and other objects deeper than the printed depth show as `[Object]`, as in `ArrayContaining [ ObjectContaining { Update: ObjectContaining { Key: [Object] } } ]`. A sample that refers to itself prints as `[Circular *1]` there, as `util.inspect()` shows it. - -With vitest (the [compatibility checks](#test-runners) run these checks with vitest and with jest on every change): - - -```typescript -import { expect, test } from 'vitest' -import { Substitute } from '@fluffy-spoon/substitute' - -interface Mailer { - send(to: string, template: 'welcome' | 'dunning', vars?: Record): Promise<{ messageId: string }> -} - -test('sends the welcome mail', async () => { - const mailer = Substitute.for() - mailer.send(expect.any(String), 'dunning').resolves({ messageId: 'm1' }) - - // the code under test - await mailer.send('ann@example.com', 'welcome', { customer: 'cus_1' }) - - mailer.received(1).send(expect.stringContaining('@'), 'welcome', expect.objectContaining({ customer: 'cus_1' })) - // SubstituteException: Expected to receive 0 method calls matching send(Any, 'welcome', Anything), but received 1. - expect(() => mailer.didNotReceive().send(expect.any(String), 'welcome', expect.anything())).toThrow('but received 1') - await expect(mailer.send('bob@example.com', 'dunning')).resolves.toEqual({ messageId: 'm1' }) -}) -``` - -`Arg` matchers work inside the matchers of jest and vitest: in `expect.objectContaining({ topic: Arg.any('string') })` or `expect.arrayContaining([{ key: Arg.any() }])`, the `Arg` matcher matches as it does elsewhere, in setups and in checks. So do `Arg` matchers in the equality of jest and vitest themselves: `expect(order).toEqual({ id: Arg.any(), total: Arg.is(total => total > 0) })` and `expect(callback).toHaveBeenCalledWith(Arg.any('string'), { id: Arg.any() })` work in a test. There, `Arg.all()` stands for one value, as an `Arg.any()` would, not for the rest of a call's arguments: `expect(callback).toHaveBeenCalledWith('a', Arg.all())` passes after `callback('a', 1)`, but fails after `callback('a', 1, 2)` and after `callback('a')`, and `expect(['level', 1, 2]).toEqual(['level', Arg.all()])` fails, too. Write `expect.anything()` for each further argument there, or look at `callback.mock.calls`. Nor do `Arg` matchers work as the property matchers of `toMatchSnapshot()` and `toMatchInlineSnapshot()`: the first run passes, but the snapshot keeps the value itself (`"id": "o-1795118127953"`) instead of the matcher, because jest and vitest keep only matchers of their own kind there, so the next run fails. Use `expect.any(String)` or `expect.anything()` in a snapshot. jest and vitest ask an `Arg` matcher through its `asymmetricMatch()` method, as they ask their own matchers, so what its predicate does to substitutes leaves no trace there either (see [Matching specific arguments](#matching-specific-arguments)). In the diff of a failing `toEqual()`, jest shows an `Arg` matcher that matches as no difference, as it does for `expect.any()`, but it prints an `Arg` matcher as an object (`Argument { "_description": "Arg.any{any}", ... }`); the library's own messages and printouts show it by its label, as before. The [compatibility checks](#test-runners) run this with jest 30, with the `expect` of jest 29 and with vitest on every change. sinon's matchers do not ask the `Arg` matchers inside them: `sinon.match({ id: Arg.any() })` compares the `Arg` matcher as a value, so it never matches. Inside a sinon matcher, use sinon's matchers (`sinon.match({ id: sinon.match.any })`). - - -```typescript -import { expect, test, vi } from 'vitest' -import { Substitute, Arg } from '@fluffy-spoon/substitute' - -test('Arg matchers inside the matchers of vitest', () => { - const producer = Substitute.for() - // the code under test - producer.send({ topic: 'orders', messages: [{ key: 'o1', value: 1 }] }) - - producer.received(1).send(expect.objectContaining({ topic: Arg.any('string') })) - producer.received(1).send({ topic: 'orders', messages: expect.arrayContaining([{ key: Arg.any(), value: Arg.is((v: number) => v > 0) }]) }) - producer.didNotReceive().send(expect.objectContaining({ topic: Arg.any('number') })) - - const repo = Substitute.for() - repo.save(expect.objectContaining({ id: Arg.any(), name: Arg.is.not((name: string) => name === '') })).returns('saved') - expect(repo.save({ id: 7, name: 'ann', extra: true })).toBe('saved') - - expect({ id: 7, name: 'ann' }).toEqual({ id: Arg.any(), name: Arg.any('string') }) - const fn = vi.fn() - fn('a', { id: 1 }) - expect(fn).toHaveBeenCalledWith(Arg.any('string'), { id: Arg.any() }) -}) -``` - -`expect.objectContaining({ id: 'c1' })` does not match a substitute whose `id` is configured to return `'c1'`. jest 30's never matches a function, and every substitute is one (see [Substitutes are functions](#substitutes-are-functions)). jest 29's and vitest's look only at the properties that a value has, and a substitute has none for its members, configured or not, only those of a mimicked object and those defined with `Object.defineProperty()`. Match such an argument with `Arg.is(customer => customer.id === 'c1')`. - -The library recognises them by their shape. A jest or vitest matcher is an object with an own `$$typeof` property equal to `Symbol.for('jest.asymmetricMatcher')` and an `asymmetricMatch` method, and a sinon matcher is an object that is not a plain object, with an own `test` method and an own `message` string, and with `and` and `or` methods. A matcher of another library in one of these shapes works as well, and so does one made by hand: - -```js -const { Substitute } = require('@fluffy-spoon/substitute') - -// an asymmetric matcher in the shape that jest and vitest give them -const even = { - $$typeof: Symbol.for('jest.asymmetricMatcher'), - asymmetricMatch: value => value % 2 === 0, - toAsymmetricMatcher: () => 'Even' -} - -const counter = Substitute.for() -counter.add(even).returns('even') -console.log(counter.add(4)) // prints even -counter.add(3) -counter.received(1).add(even) -counter.received(2).add(even) // throws SubstituteException: Expected to receive 2 method calls matching add(Even), but received 1. -``` - -In TypeScript, vitest types its matchers `any`, and so does `@types/jest` for jest's global `expect`, so they fit every parameter, also where they can never match (`expect.any(Number)` for a string). With `@jest/globals`, they are typed `AsymmetricMatcher`, which only parameters typed `unknown`, `any` or `object` (or another type that such a matcher fits) take. Cast them for other parameters: `expect.any(String) as never` (`as string` does not compile). `@types/sinon` types sinon's matchers as `SinonMatcher`. Like `AsymmetricMatcher`, it is only accepted by parameters typed `unknown`, `any`, `object` or `{}` (also `Object`, `Record`, and unions with one of them, such as an optional `object` parameter). Cast it for any other parameter, in setups and in checks: `sinon.match.has('err') as never` for an options object such as `{ err?: string }`, an interface or `Error`, and `sinon.match.string as never` for a string. `Arg` matchers are typed for the parameter that they replace, and do not depend on a test runner, so prefer them where you write new tests: `Arg.any('string')`, `Arg.is(vars => vars.customer === 'cus_1')`. - -## How arguments are compared -Arguments that are not matchers are compared with deep strict equality, the rule of `assert.deepStrictEqual` (`util.isDeepStrictEqual`). Objects and arrays are equal when they have the same prototype and their own enumerable properties (with string or symbol keys) are equal. `NaN` equals `NaN`, but `0` and `-0` are different. Where Node.js changed the rule, the library follows the running version: two invalid `Date`s are different up to Node.js 22 and equal from Node.js 24 on, and two cyclic objects whose cycles have a different shape are equal up to Node.js 22 and different from Node.js 24 on. Substitutes are compared by identity and never member by member. - -Deep strict equality reads the own enumerable properties of both values, so it runs their getters. What such a getter does to a substitute while the library compares arguments, for a call, a setup or a check, leaves no trace, as a [predicate's look](#matching-specific-arguments) does: its reads, calls and assignments are not recorded, setups still answer them, and they use up no values of a `returns()` or `resolves()` sequence. What the code under test itself does through the getter is recorded as usual. - -```js -const { Substitute, Arg } = require('@fluffy-spoon/substitute') - -const pricing = Substitute.for() -pricing.priceOf('A').returns(10, 20) -// a cart line whose total asks the pricing service -const line = qty => ({ sku: 'A', qty, get total() { return pricing.priceOf('A') * qty } }) - -const cart = Substitute.for() -cart.add(line(1)) -cart.add(line(2)) -// compares line(2) with the received line(2), which reads total on both -cart.received(1).add(line(2)) - -// the library's comparisons left no trace on pricing -pricing.didNotReceive().priceOf(Arg.any()) -console.log(pricing.priceOf('A')) // prints 10 -``` - -Arguments are compared position by position, up to the longer of the two argument lists. An argument that one side leaves out at the end counts as `undefined` there: it matches only a literal `undefined` or a matcher that accepts `undefined`, such as `Arg.any()`, `Arg.any('undefined')`, `Arg.is(value => value === undefined)` or `Arg.any.not('number')`. A predicate that throws for `undefined` (`Arg.is(name => name.length > 0)`) does not match, as always. So `f(1)` and `f(1, undefined)` are the same call: they match the same setups and checks, return the same [auto-substitute](#auto-substitutes-and-nested-members), and are one setup in the [`configure`](#re-configuring-a-call-configure) view, where a setup of one replaces a setup of the other. Arguments with values still count: `f(1)` and `f(1, 2)` are different calls, either way round. This applies to the arguments themselves only. Inside an array or an object, deep strict equality decides, so `[1]` and `[1, undefined]` are different, and so are `{ id: 1 }` and `{ id: 1, name: undefined }`. Failure messages show each call as it was made. - -```typescript -import { Substitute, Arg } from '@fluffy-spoon/substitute' - -interface Cache { - get(key: string, options?: { fresh: boolean }): string -} - -const cache = Substitute.for() -cache.get('a', Arg.any()).returns('any options') -cache.get('b', undefined).returns('no options') -cache.get('c', Arg.any('object')).returns('with options') - -// the code under test leaves the options out -console.log(cache.get('a')) // prints any options -console.log(cache.get('b')) // prints no options -// Arg.any('object') does not accept undefined -console.log(cache.get('c') === 'with options') // prints false - -cache.received(1).get('b', undefined) -cache.received(3).get(Arg.any(), Arg.any()) -cache.didNotReceive().get(Arg.any(), Arg.any('object')) -``` - -So a check like `didNotReceive().get('a', Arg.any())` fails after `get('a')`, and a matcher setup that accepts `undefined` answers calls that leave the argument out, which matters when you [re-configure such a call](#re-configuring-a-call-configure). - -Errors follow Node.js' rule, too. An object that inherits from `Error.prototype` and has the `Symbol.toStringTag` `'Error'` is compared like an error (its `name` and `message` count), so it can be equal to a native error with the same message. Objects that `Object.prototype.toString` shows as `[object Object]` are compared by their keys alone: error-like objects without that tag, and native errors whose `Symbol.toStringTag` is `'Object'`. On Node.js 24 and newer, Node.js still compares a native error with that tag as an error when it is the first argument of `isDeepStrictEqual`, so there the result can depend on the order. The library then passes the value of the setup or the check first, and for [auto-substitutes](#auto-substitutes-and-nested-members) the value of the earlier call. - -```js -const { Substitute } = require('@fluffy-spoon/substitute') - -const handler = Substitute.for() -handler.handle(new Error('timeout')).returns('retry') - -// not a native error, but deep strictly equal to the error above -const errorLike = Object.create(Error.prototype, { - message: { value: 'timeout' }, - [Symbol.toStringTag]: { value: 'Error' } -}) -console.log(handler.handle(errorLike)) // prints retry -``` - -Deep strict equality cannot see `#private` fields or other internal state. So all instances of a class that keeps its state only in `#private` fields are equal to each other. The same goes for some built-in objects, depending on the Node.js version: two `Blob`s of the same size and type are equal, whatever their bytes (a `Blob` of another size or type is not), and so are two `File`s, which from Node.js 24 on must also have the same name and the same `lastModified` time (which is the time a `File` is made, unless it is given one; before Node.js 24, the name and the time do not count); any two `AbortController`s, any two `EventTarget`s and any two `AbortSignal`s of the same kind that are not aborted, on every Node.js version that has them: two signals of controllers, or two of `AbortSignal.timeout()`, whatever their delays (a signal of `AbortSignal.timeout()` or of `AbortSignal.any()` is not equal to a controller's), any two `Headers` and any two `URLSearchParams` from Node.js 20 on, and any two `FormData`, fetch `Request`s and `Response`s from Node.js 24 on (two URLs, though, are equal only when their addresses are, on every version). So a check that the code under test passed your own controller's `AbortSignal` to `fetch()`, an AWS SDK client or axios passes for the signal of any controller, and one with your own `AbortSignal.timeout(5000)` for any timeout signal. For such values, pass the same instance, or match with `Arg.is()`, which can compare by identity: `Arg.is(signal => signal === controller.signal)`. A predicate cannot wait for what a `Blob` holds (`blob.text()` returns a promise), so to check its bytes, take the `Blob` out with a predicate and read it afterwards: `let sent; storage.received(1).upload(Arg.is(blob => { sent = blob; return true }))`, then `await sent.text()`. - -```js -const { Substitute, Arg } = require('@fluffy-spoon/substitute') - -const storage = Substitute.for() -const controller = new AbortController() -// the code under test passes a signal of its own -storage.getObject({ Key: 'report.csv' }, { abortSignal: new AbortController().signal }) - -// any two signals of controllers that are not aborted are equal, so this passes -storage.received(1).getObject({ Key: 'report.csv' }, { abortSignal: controller.signal }) -// compare the signal by identity to check that it is yours -storage.didNotReceive().getObject({ Key: 'report.csv' }, { abortSignal: Arg.is(signal => signal === controller.signal) }) - -// a signal of AbortSignal.timeout() equals only other such signals -storage.getObject({ Key: 'audit.csv' }, { abortSignal: AbortSignal.timeout(5000) }) -storage.received(1).getObject({ Key: 'audit.csv' }, { abortSignal: AbortSignal.timeout(100) }) -storage.didNotReceive().getObject({ Key: 'audit.csv' }, { abortSignal: controller.signal }) - -// two Blobs of the same size and type are equal, whatever they hold -storage.upload(new Blob(['a,b'])) -storage.received(1).upload(new Blob(['x,y'])) -storage.didNotReceive().upload(new Blob(['a,b,c'])) -storage.didNotReceive().upload(new Blob(['a,b'], { type: 'text/csv' })) -// to check its bytes, take it out with a predicate and read it -let sent -storage.received(1).upload(Arg.is(blob => { sent = blob; return true })) -sent.text().then(text => console.log(text)) // prints a,b -``` - -A class whose instances keep their state in `#private` fields: - -```typescript -import { Substitute, Arg } from '@fluffy-spoon/substitute' - -class Money { - #cents: number - constructor(cents: number) { this.#cents = cents } - get cents() { return this.#cents } -} - -interface Bank { - pay(amount: Money): string -} - -const bank = Substitute.for() -bank.pay(new Money(100)).returns('paid') -// all Money instances are equal to each other -console.log(bank.pay(new Money(5))) // prints paid - -const checkedBank = Substitute.for() -checkedBank.pay(Arg.is(amount => amount.cents === 100)).returns('paid') -console.log(checkedBank.pay(new Money(5)) === 'paid') // prints false -console.log(checkedBank.pay(new Money(100))) // prints paid -``` - -A value that cannot be read, such as an object with a getter that throws, a revoked proxy, or a proxy whose keys cannot be listed (its `ownKeys` or `getOwnPropertyDescriptor` trap throws), is equal only to itself: Node.js' deep equality throws when it has to read such a value, which counts as unequal, and it does not read a value that it compares with itself. So the same value matches, and so does a new array or object that holds that same value, but another such value never does. This is decided again at each comparison: once the value can be read, it is compared by its contents, like any other value, so it matches a setup made with an equal object, and a setup made while it could not be read matches calls with an equal object from then on. Each comparison with another value can read it again (Node.js' deep equality stops at the first getter that throws), so such a getter may be read several times for each call, setup or check that passes the value: a call or a setup is compared with the setups of its member and with the calls that created the member's auto-substitutes (the call of each setup among them), and a check with each received call of its member. Such a value is never taken for a [matcher](#matchers-of-test-runners), so it matches by identity next to matchers, too, at the top level and inside objects and arrays: `repository.save(draft, Arg.any())` and `repository.load({ entity: draft, id: Arg.any() })`, where `draft` is a revoked proxy, such as an immer draft after `produce()` has finished, or a proxy whose keys cannot be listed. Such a setup answers, and such a check counts, the calls with that same value. A revoked proxy of a function (`Proxy.revocable(function connection() {}, {})`) is a value like any other as well, also as the value of a setup (`pool.acquire().returns(connection)`, which still answers that proxy after `revoke()`), of a member or of a mimicked instance. It prints as ``, except on Node.js versions whose `util.inspect()` cannot print a revoked proxy (16.9 and older, for example): there, a call with one prints its arguments as `(...)` in a path, and as `` in a failure message. - -```js -const { Substitute, Arg } = require('@fluffy-spoon/substitute') - -// a record whose getter throws until it is loaded -const unloaded = () => Object.defineProperty({}, 'name', { enumerable: true, get() { throw new Error('not loaded') } }) - -const cache = Substitute.for() -const user = unloaded() -cache.store([user]).returns('stored') - -console.log(cache.store([user])) // prints stored -console.log(cache.store([unloaded()]) === 'stored') // prints false - -// once the record can be read, it is compared by its contents -let loaded = false -const record = Object.defineProperty({}, 'name', { enumerable: true, get() { if (loaded) return 'ann'; throw new Error('not loaded') } }) -cache.load(record) // the code under test passes the record before it is loaded -loaded = true -cache.load({ name: 'ann' }).returns('loaded') -console.log(cache.load(record)) // prints loaded - -// a setup made before the record can be read matches equal records once it can -let ready = false -const order = Object.defineProperty({}, 'id', { enumerable: true, get() { if (ready) return 7; throw new Error('not loaded') } }) -cache.save(order).returns('saved') -ready = true -console.log(cache.save({ id: 7 })) // prints saved - -// a revoked proxy, such as an immer draft after produce() has finished, next to a matcher -const { proxy: draft, revoke } = Proxy.revocable({}, {}) -revoke() -const repository = Substitute.for() -repository.save(draft, Arg.any()).returns('saved') -console.log(repository.save(draft, 'users')) // prints saved -repository.received(1).save(draft, Arg.any()) -console.log(String(repository.load({ entity: draft }))) // prints @Substitute.load({ entity: }) - -// a proxy whose keys cannot be listed, next to a matcher -const locked = new Proxy({ id: 1 }, { ownKeys() { throw new Error('locked') } }) -repository.find({ entity: locked, page: Arg.any() }).returns('found') -console.log(repository.find({ entity: locked, page: 2 })) // prints found -repository.didNotReceive().find({ entity: locked, page: Arg.any() }) // throws SubstituteException -``` - -Setups, received calls and auto-substitutes keep the argument objects themselves, and compare them as they are at the time of each call or check. So when an object changes after it was passed, a setup made with it matches calls with an object equal to its new contents, also inside a new array or object, and no longer calls with an object equal to its old contents. A check compares the arguments of the received calls as they are when the check runs: if the code under test changes an object after passing it, check its new value. An [auto-substitute](#auto-substitutes-and-nested-members) keeps the arguments of the call that created it: a call that no setup answers gets the first auto-substitute of its member, in the order they were created, whose arguments are equal to its own at that moment, or a new one. A call that gets an existing auto-substitute creates none, so its own arguments do not count there later. A check through a call with matchers counts the calls of the auto-substitute that each matching received call got, also when that call's arguments changed afterwards: - -```js -const { Substitute, Arg } = require('@fluffy-spoon/substitute') - -const repository = Substitute.for() -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 saved -console.log(repository.save({ name: 'ann' }) === 'saved') // prints false -// the first of these calls passed user itself, whose name is 'bob' now -repository.received(2).save({ name: 'bob' }) -repository.received(1).save({ name: 'ann' }) - -const api = Substitute.for() -const query = { page: 1 } -const firstPage = api.list(query) -query.page = 2 -console.log(api.list({ page: 2 }) === firstPage) // prints true - -// a call that gets an existing auto-substitute creates none -const filter = { page: 3 } -const thirdPage = api.list({ page: 3 }) -console.log(api.list(filter) === thirdPage) // prints true -filter.page = 4 -console.log(api.list({ page: 4 }) === thirdPage) // prints false - -// the code under test runs two queries, then changes the second filter -const db = Substitute.for() -const users = { table: 'users' } -const orders = { table: 'orders' } -db.query(users).run() -db.query(orders).run() -orders.table = 'users' -// both calls match now, and each one's auto-substitute was run once -db.query(Arg.any()).received(2).run() -// a concrete call gets the first auto-substitute equal to it: the one of users -db.query({ table: 'users' }).received(1).run() -``` - -## Match order -When several setups match a call, the most specific one wins: - -1. a setup whose arguments are all literal values, -2. then a setup with at least one `Arg.any()` / `Arg.is()` matcher, also inside an object or array (or literals followed by `Arg.all()`), -3. then a setup with `Arg.all()` as its only argument. - -Among setups of the same kind, the one configured last wins, so a later setup overrides an earlier one. - - -```typescript -calculator.add(1, 3).returns(1337) -calculator.add(Arg.all()).returns(10) -calculator.add(Arg.is(a => a > 100), Arg.any()).returns(100) - -// literal arguments win over matchers, and matchers win over Arg.all() -console.log(calculator.add(1, 3)) // prints 1337 -console.log(calculator.add(200, 3)) // prints 100 -console.log(calculator.add(5, 2)) // prints 10 - -// among setups with matchers, the newest one wins -calculator.add(Arg.any(), Arg.is(b => b > 10)).returns(-1) -console.log(calculator.add(200, 30)) // prints -1 -console.log(calculator.add(200, 3)) // prints 100 -``` - -## Re-configuring a call (configure) -Outside of a setup, a call whose literal arguments match an existing setup is a real call: it returns the configured value. So writing the call out again does not configure it again, and what `.returns()` does then depends on the configured value: - -* A primitive like `10`, a plain object or an array has no `.returns()`, so you get a `TypeError`. -* A substitute that you created with `Substitute.for()` has a member called `returns`, like every other name. `.returns(x)` is recorded as a call of that member, and nothing is configured. Nothing fails, and TypeScript does not catch it either. -* An auto-substitute (an unconfigured member of a substitute) is configured itself: `.returns(x)` configures that member, not the call. - -This also happens when a matcher setup answers a call that leaves out an argument that the matcher accepts as `undefined` (see [How arguments are compared](#how-arguments-are-compared)): after `calculator.multiply(1, Arg.any()).returns(10)`, `calculator.multiply(1)` returns 10, so `calculator.multiply(1).returns(1)` throws a `TypeError`. Likewise, `f()` is the call `f(undefined)`, so `f(undefined).returns(a)` followed by `f().returns(b)` is one call written twice. Make the literal setup first, or use `configure`. - -Use `sub[configure]()` instead. It gives a view of the substitute in which every call and property read is a setup: it never runs an existing setup and is never recorded as a received call. - - -```typescript -import { configure } from '@fluffy-spoon/substitute' - -calculator.add(Arg.all()).returns(10) -// add(1, 3) matches the setup above, so it returns 10 and has no .returns(): -calculator.add(1, 3).returns(1337) // throws TypeError: calculator.add(...).returns is not a function - -calculator[configure]().add(1, 3).returns(1337) -console.log(calculator.add(1, 3)) // prints 1337 -console.log(calculator.add(5, 2)) // prints 10 - -// the same applies to changing a value that is already configured, and to properties -calculator.isEnabled.returns(true) -calculator[configure]().isEnabled.returns(false) -console.log(calculator.isEnabled) // prints false -``` - -```js -const { Substitute, Arg, configure } = require('@fluffy-spoon/substitute') - -const calculator = Substitute.for() -calculator.multiply(1, Arg.any()).returns(10) -// multiply(1) leaves out the second argument, which Arg.any() accepts -calculator.multiply(1).returns(1) // throws TypeError: calculator.multiply(...).returns is not a function - -calculator[configure]().multiply(1).returns(1) -console.log(calculator.multiply(1)) // prints 1 -console.log(calculator.multiply(1, 5)) // prints 10 -``` - -Calls with argument matchers are always setups (see [What counts as a call](#what-counts-as-a-call)), so a catch-all setup *after* a specific one needs no `configure`. In TypeScript, the `configure` view only offers the setup methods. - -A setup in the `configure` view can go through a member or a call that already answers with a value. If that value is a substitute, the setup goes to that substitute, which keeps its other setups. If it is a real value (a plain object, an array, a primitive), or the member is configured with `throws()`, `resolves()`, `rejects()` or `mimicks()`, its members cannot be configured, and the setup throws a `SubstituteException` that says so. Nothing is replaced in that case. Members and calls that do not answer with a value yet are configured as usual. - -```js -const { Substitute, configure } = require('@fluffy-spoon/substitute') - -const repository = Substitute.for() -repository.find(2).returns('two') - -const container = Substitute.for() -container.getRepository().returns(repository) - -// getRepository() answers with a substitute, so the setup goes to that substitute -container[configure]().getRepository().find(1).returns('one') -console.log(container.getRepository() === repository) // prints true -console.log(repository.find(1)) // prints one -console.log(repository.find(2)) // prints two - -container.settings.returns({ port: 80 }) -container[configure]().settings.port.returns(1) // throws SubstituteException: settings returns { port: 80 }, which is not a substitute -``` - -For a call without matchers, the setup that answers the call counts, also a matcher setup: after `lookup.get(Arg.any()).returns(repository)`, `lookup[configure]().get(5).find(3).returns('three')` configures `repository.find(3)`. - -# Partial mocks -With partial mocks you always start with a true substitute where everything is mocked, and then opt out of substitutions in certain scenarios: per call with `mimicks()`, or for a whole instance with `[mimick]()`. The examples use this implementation: - - -```typescript -class RealCalculator implements Calculator { - isEnabled = true - add(a: number, b: number) { return a + b } - subtract(a: number, b: number) { return a - b } - divide(a: number, b: number) { return a / b } - async heavyOperation(...numbers: number[]) { return numbers.reduce((total, n) => total + n, 0) } -} - -const realCalculator = new RealCalculator() -``` - - -```typescript -// let the subtract method always use the real method -calculator.subtract(Arg.all()).mimicks(realCalculator.subtract) -console.log(calculator.subtract(20, 10)) // prints 10 -console.log(calculator.subtract(1, 2)) // prints -1 - -// for the add method, use the real method only when the first argument is less than 10 -// else, always return 1337 -calculator.add(Arg.is(x => x < 10), Arg.any()).mimicks(realCalculator.add) -calculator.add(Arg.is(x => x >= 10), Arg.any()).returns(1337) -console.log(calculator.add(5, 100)) // prints 105 -console.log(calculator.add(210, 7)) // prints 1337 - -// for the divide method, use the real method only for these exact arguments -calculator.divide(10, 2).mimicks(realCalculator.divide) -calculator.divide(Arg.all()).returns(1338) -console.log(calculator.divide(10, 2)) // prints 5 -console.log(calculator.divide(10, 5)) // prints 1338 -``` - -`sub[mimick](instance)` hands everything that is not configured to a real instance: property reads return the instance's values, method calls run the instance's methods (with `this` being the instance, unless you pass another one with `.call()` or `.apply()`), and assignments write to the instance. If the instance is a function, calling the substitute calls it, with the `this` of the call. Members that the instance does not have read as `undefined`. Setups still win, and every call is recorded, so you can verify it. Because real calls are passed on to the instance, configure a mimicked substitute through [`[configure]()`](#re-configuring-a-call-configure). - - -```typescript -import { mimick, configure } from '@fluffy-spoon/substitute' - -calculator[mimick](realCalculator) -console.log(calculator.add(2, 3)) // prints 5 -console.log(calculator.isEnabled) // prints true - -calculator[configure]().divide(Arg.all()).returns(0) -console.log(calculator.divide(1, 1)) // prints 0 - -// the code under test sets a property -const disable = (c: Calculator) => { c.isEnabled = false } -disable(calculator) -console.log(realCalculator.isEnabled) // prints false - -calculator.received().add(2, 3) -calculator.received().isEnabled = false -``` - -A method of the instance that returns the instance itself, as fluent APIs do (a builder's `return this`, an `EventEmitter`'s `on()` and `once()`, a stream's `setEncoding()`), answers with the substitute instead, and so does a getter or a property of the instance whose value is the instance. So a chain such as `socket.setEncoding('utf8').on('data', onData)` stays on the substitute: each of its calls is recorded, can be checked, and can be configured. The method still runs with the instance as `this`, so the instance changes as it would without the substitute. Only the instance itself is replaced: a promise that resolves to it (an `async` method that returns `this`) and other objects that hold it are returned as they are, and a method called with another `this` (`.call(other)`) returns what it returns. - -```js -const { PassThrough } = require('stream') -const { Substitute, Arg, mimick } = require('@fluffy-spoon/substitute') - -// the code under test sets up a socket in one chain -const wire = (socket, onData) => socket.setEncoding('utf8').on('data', onData).on('end', () => socket.end()) - -const real = new PassThrough() -const socket = Substitute.for() -socket[mimick](real) - -console.log(wire(socket, () => { }) === socket) // prints true -socket.received(1).setEncoding('utf8') -socket.received(1).on('end', Arg.any()) -// the real stream did the work -console.log(real.listenerCount('data')) // prints 1 -``` - -A method of a mimicked instance reads as a member handle that calls the instance's function as it was when the handle was read, as `const original = obj.method` does on an ordinary object. So code that wraps a member and forwards to it, as instrumentation libraries (OpenTelemetry's instrumentations, shimmer), retry decorators and spies do, works on a mimicked substitute: `const original = client.query; client.query = function (...args) { return original.apply(this, args) }` writes the wrapper to the instance, a call of `client.query()` runs the wrapper, the wrapper runs the original function once, and the call is recorded once. In detail: - -* While the instance keeps the same function, every read gives the same handle (`sub.query === sub.query`). Once the member is replaced, a read gives another handle, as on an ordinary object, and a getter of the instance that gives a new function at every read gives a new handle at every read (it runs once per call). -* A call through the original handle, made while a call of the same member of the same substitute is handed to the instance (by a wrapper that forwards to the original with `apply()`, `call()`, a direct call, a bound original or `new`, also through several wrappers), is part of that call: it is not recorded again, it is not compared with the setups again, and it runs the original function. -* A call through the original handle from anywhere else is a call like any other: from the test, or from an `async` wrapper after its first `await`, when the call of the wrapper has returned. It is recorded and compared with the setups, and then it runs the original function, not the current one (after `sub.query = sql => 'replaced'`, `original('x')` runs the original). So an `async` wrapper that awaits before it calls the original records that call as a second call. -* Setups still answer first (`sub[configure]().query('SELECT 1').returns(rows)`), before the wrapper on the instance runs, and also through the original handle. -* Assigning one of the substitute's own handles back (`client.query = original`, as the restore of a spy does) puts the function itself back on the instance, and `client.query === original` again. A handle that the instance holds under another name (`real.alias = client.query`) calls the function that it stands for, and `client.alias('x')` is recorded as a call of `alias`. -* A handle read before the substitute mimicked the instance, or while it mimicked another one, calls what the current instance has. -* A fluent method stays fluent through a wrapper: with an `EventEmitter` mimicked and its `on()` wrapped, `emitter.on('a', f).on('b', g)` returns the substitute (see above). -* The calls that a mimicked method makes through `this` are not recorded, as `this` is the instance (see above), and neither is recursion through `this`. That holds as well when a wrapper or spy replaced the member that it calls (`jest.spyOn()`, `vi.spyOn()`, node:test's `mock.method()`, sinon on the instance, or `const o = sub.validate; sub.validate = function (...a) { return o.apply(this, a) }`): while a call of the substitute is handed to the instance, the instance's own call of that member through `this` runs the wrapper or spy, which still sees it, but it is not recorded and no setup answers it, as without the wrapper. Two limits: it holds only while the call is handed to the instance, so in an `async` method, the calls through `this` after its first `await` go through the wrapper to the substitute and are recorded; and it holds only for the member that the wrapper replaced, so a wrapper of one member that calls a stored handle of another (`const a = sub.a; sub.b = function (x) { return a.call(this, x) }`) records that call of `a`, as before. - -A frozen instance refuses the assignment with a `TypeError` (`Cannot assign to read only property 'query' of object`). The spies of jest, vitest, node:test and sinon put their spy on the instance in the same way, behind the substitute; see [Test runners](#test-runners) for what each of them does, also on a frozen instance. - -```js -const { Substitute, Arg, configure, mimick } = require('@fluffy-spoon/substitute') - -// an instrumentation library wraps the client's query method -function instrument(client, spans) { - const original = client.query - client.query = function (...args) { - spans.push(args[0]) - return original.apply(this, args) - } -} - -const real = { query: sql => 'rows for ' + sql } -const client = Substitute.for() -client[mimick](real) -client[configure]().query('SELECT 0').returns('configured') -const spans = [] -instrument(client, spans) - -console.log(client.query('SELECT 1')) // prints rows for SELECT 1 -// a setup answers before the instance, and so before the wrapper on it -console.log(client.query('SELECT 0')) // prints configured -console.log(spans) // prints [ 'SELECT 1' ] -// each call is recorded once -client.received(1).query('SELECT 1') -client.received(2).query(Arg.any()) -``` - -The instance's own calls through `this` stay its own, also through a wrapper: - -```js -const { Substitute, configure, mimick, clearReceivedCalls } = require('@fluffy-spoon/substitute') - -class OrderService { - place(order) { return this.validate(order) ? 'placed' : 'rejected' } - validate(order) { return order.id > 0 } -} -const service = Substitute.for() -service[mimick](new OrderService()) -service[configure]().validate({ id: 0 }).returns(true) -// a wrapper on validate(), as instrumentation or a spy puts it there -const validate = service.validate -const seen = [] -service.validate = function (...args) { seen.push(args[0].id); return validate.apply(this, args) } -service[clearReceivedCalls]() - -// place() calls this.validate(): the wrapper sees it, the setup does not answer it, and it is not recorded -console.log(service.place({ id: 0 })) // prints rejected -console.log(seen) // prints [ 0 ] -service.didNotReceive().validate({ id: 0 }) -// a call through the substitute is answered by the setup first, and recorded -console.log(service.validate({ id: 0 })) // prints true -service.received(1).validate({ id: 0 }) -``` - -In TypeScript, `[mimick]()` takes a partial instance of an object type, so `client[mimick]({ baseUrl: '' })` compiles for a `Client` that has other members, too. The members of an object literal get their types from the substituted type (`calculator[mimick]({ add: (a, b) => a + b })` types `a` and `b` as numbers), and members that the type does not have, or of another type, are rejected. Function types and other types with call or construct signatures, arrays, tuples and primitives take a whole instance. In generic code, the instance is a `T`: in `function delegate(sub: SubstituteOf, instance: T)`, `sub[mimick](instance)` compiles, also for a substitute of `T | undefined` or `T | null` (`SubstituteOf`), and a `Partial` needs a cast to `T`. TypeScript does not accept an object literal for a type that declares a member of `Object.prototype` with another type, such as `Date` with its `valueOf(): number`: `date[mimick]({ getTime: () => 0 })` does not compile, so pass a real instance (`date[mimick](new Date(0))`) or cast. - - -```typescript -import { mimick } from '@fluffy-spoon/substitute' - -interface Client { - baseUrl: string - timeout?: number - get(path: string): Promise -} - -const client = Substitute.for() -client[mimick]({ get: async path => `GET ${path}` }) -client.get('/users').then(response => console.log(response)) // prints GET /users - -calculator[mimick]({ add: (a, b) => a + b }) -console.log(calculator.add(2, 3)) // prints 5 - -// @ts-expect-error a Client has no member called baseURL -Substitute.for()[mimick]({ baseURL: '' }) -// @ts-expect-error baseUrl is a string -Substitute.for()[mimick]({ baseUrl: 1 }) -``` - -In an object literal given to `[mimick]()`, `this` is the partial type (`Partial` below), so a fluent method that returns `this` does not compile as it is (TypeScript reports that the return types `Partial` and `Reply` are incompatible). Cast it (`status() { return this as Reply }`), let the method return the substitute (`status: () => reply`), or pass a real instance. The same goes for an express `Response` (`res[mimick]({ status() { return this as Response }, json() { return this as Response } })`) and for query builders. A method that returns `this` answers with the substitute either way (see above), so the chain stays on the substitute. - -```typescript -import { Substitute, Arg, mimick } from '@fluffy-spoon/substitute' - -interface Reply { - status(code: number): this - json(body: unknown): this -} - -// the code under test answers in one chain -const notFound = (reply: Reply) => reply.status(404).json({ error: 'not found' }) - -const reply = Substitute.for() -// in the object literal, `this` is a Partial: cast it to return it from a fluent method -reply[mimick]({ status() { return this as Reply }, json() { return this as Reply } }) -console.log(notFound(reply) === reply) // prints true -reply.received(1).status(404) -reply.received(1).json(Arg.any()) - -// or let the methods return the substitute -const other = Substitute.for() -other[mimick]({ status: () => other, json: () => other }) -console.log(notFound(other) === other) // prints true -other.received(1).json(Arg.any()) - -// @ts-expect-error `this` is a Partial, which is not a Reply -Substitute.for()[mimick]({ status() { return this } }) -``` - -A substitute that mimicks an object enumerates like it. `Object.keys(sub)`, `Object.entries(sub)`, spread (`{ ...sub }`), `Object.assign({}, sub)` and `for...in` see the instance's enumerable own keys, strings and symbols; its non-enumerable keys are not listed. `Reflect.ownKeys(sub)` lists the same keys, followed by `length` and `name`, which are not enumerable and which every substitute has (see [Freezing, defined properties and `in`](#freezing-defined-properties-and-in)); for an instance with an enumerable own `name` or `length`, that key is listed once, with the instance's descriptor. Reading their values goes through the substitute, so setups come first, and the reads are recorded. `Object.getOwnPropertyDescriptor(sub, key)` gives the instance's descriptor, with `configurable: true`: for a plain value with the value on the instance, and for an accessor with its getter and setter. For a method that the instance has as an enumerable own property, the descriptor's value is the member handle (`sub.key`, see above), not the instance's function, so that tools that wrap the method go through the substitute. Reading a descriptor records nothing. `Object.defineProperty(sub, key, descriptor)` defines the member on the instance, as an assignment writes to it (with one of the substitute's own handles as the value, it defines the handle's function), and `delete sub.key` deletes the instance's member. A descriptor with `configurable: false`, a descriptor without `configurable` for a key that the instance does not have as its own (which then defaults to `false`, as on any object: `Object.defineProperty(sub, 'flag', { value: true })`), and one that the instance refuses (a frozen instance) define the property on the substitute itself instead, which then reports it as on a plain object (`hasOwnProperty`, its descriptor, `Reflect.ownKeys()`, and a `TypeError` for a redefinition that it forbids); see [Freezing, defined properties and `in`](#freezing-defined-properties-and-in). Keys that the instance has as its own, and descriptors with `configurable: true` (as `vi.spyOn()` and node:test's `mock.method()` define them), go to the instance. `JSON.stringify(sub)` gives what `JSON.stringify(instance)` gives: the result of the instance's own `toJSON()`, or the instance's fields as they are on the instance, without setups and without recording reads. A substitute that mimicks a function lists the function's enumerable own keys as well (its own `length` and `name` stay `0` and `''`), but `JSON.stringify()` gives its printout. Without a mimicked object, a substitute has no enumerable own keys. - -```js -const { Substitute, configure, mimick } = require('@fluffy-spoon/substitute') - -const config = Substitute.for() -config[mimick]({ port: 80, host: 'localhost' }) -config[configure]().host.returns('example.org') - -console.log(Object.keys(config)) // prints [ 'port', 'host' ] -console.log(Reflect.ownKeys(config)) // prints [ 'port', 'host', 'length', 'name' ] -console.log({ ...config }) // prints { port: 80, host: 'example.org' } -console.log(JSON.stringify(config)) // prints {"port":80,"host":"localhost"} -config.received(1).port -``` - -In the `configure` view, a setup through a member of the instance whose value is a substitute goes to that substitute, and from then on the member reads as that substitute. The members of a real value of the instance cannot be configured: with `sub[mimick]({ settings: { port: 80 } })`, `sub[configure]().settings.port.returns(1)` throws a `SubstituteException`. Configure the whole member instead: `sub[configure]().settings.returns({ port: 1 })`. A setup through a method of the instance, like `sub[configure]().load().size.returns(1)`, does not run the real method. It creates a setup for `load()`, which from then on answers that call instead of the instance. - -The string `mimick` is not part of the API (any more): `sub.mimick(...)` is an ordinary member, like every name except the [conflicting names](#names-that-conflict-with-the-library). - -# Auto-substitutes and nested members -A member or call that is not configured returns an auto-substitute: a substitute of its own, created the first time and then reused. The same member, or the same method with equal arguments, always gives the same auto-substitute. So the code under test can use nested members without crashing, and you can configure and verify them: - -```js -const { Substitute } = require('@fluffy-spoon/substitute') - -const app = Substitute.for() -console.log(app.logger === app.logger) // prints true -console.log(app.getCalculator() === app.getCalculator()) // prints true - -app.getCalculator().add(1, 2).returns(99) -console.log(app.getCalculator().add(1, 2)) // prints 99 - -// the code under test logs a message -app.logger.info('started') - -app.logger.received().info('started') -app.logger.didNotReceive().info('stopped') -``` - -Setups and calls never leak between members: `app.add(1, 2).returns(99)` does not configure `app.getCalculator().add(1, 2)`, and the other way round. Calls with different arguments get different auto-substitutes, except after a nested setup through a call with matchers: after `io.to(Arg.any()).emit(Arg.all()).returns(true)`, every call that `to(Arg.any())` matches answers the same substitute, `io.to('room-a') === io.to('room-b')`, as in NSubstitute (see [Through a call with matchers](#through-a-call-with-matchers) for what a check through `io.to('room-b')` counts then). `String(app.logger)` and `console.log(app.logger)` show the path of an auto-substitute, `@Substitute.logger`, and what it received and how it is configured (see [Printing a substitute](#printing-a-substitute)). - -**Typing limitation:** in TypeScript, nested auto-substitutes are typed as plain values, not as substitutes, so `app.getCalculator().add(1, 2).returns(99)` and `app.logger.received()` do not compile. They do work at runtime (in JavaScript, or through a cast through `unknown`, as a [check through a call with matchers](#through-a-call-with-matchers) needs: `(app.logger as unknown as SubstituteOf).received().info('started')`). In TypeScript, configure the member to return a substitute you create yourself; that is fully typed: - -```typescript -import { Substitute } from '@fluffy-spoon/substitute' - -interface Logger { info(message: string): void } -interface Calculator { add(a: number, b: number): number } -interface App { - logger: Logger - getCalculator(): Calculator -} - -const app = Substitute.for() -const logger = Substitute.for() -const calculator = Substitute.for() -app.logger.returns(logger) -app.getCalculator().returns(calculator) - -calculator.add(1, 2).returns(99) -console.log(app.getCalculator().add(1, 2)) // prints 99 - -app.logger.info('started') -logger.received().info('started') -``` - -## Fluent interfaces -A fluent method returns the object that it is called on, so that the code under test can chain calls: `reply.code(404).send(body)` in fastify, `span.setAttribute(key, value).setStatus(status)` in OpenTelemetry, `where()` and `first()` of a query builder. On a substitute, a method that is not configured returns its auto-substitute instead, so the next call of the chain is a call of that auto-substitute, `reply.code(404)`, and not of `reply`: `reply.received(1).send(body)` fails. When a check fails because the substitute has no record of the member at all, while a member of that name was called on one of its auto-substitutes, the message ends with where it was called, and what to do: - -```js -const { Substitute } = require('@fluffy-spoon/substitute') - -// the code under test answers in one chain -const notFound = reply => reply.code(404).send({ error: 'not found' }) - -const reply = Substitute.for() -notFound(reply) -reply.received(1).send({ error: 'not found' }) // throws SubstituteException -``` - - -```text -SubstituteException: Call count mismatch in @Substitute.send: -Expected to receive 1 property read or method call matching send, but received none. -send was not called on @Substitute itself, but on a substitute further down: @Substitute.code(404).send(...). A call that is not configured answers a new substitute. For a fluent API, make the method return the substitute (sub.code(Arg.all()).returns(sub)) or mimick an instance whose methods return this. -``` - -So configure the fluent methods to return the substitute, or [mimick](#partial-mocks) an instance whose methods return `this`, which then answer with the substitute: - -```js -const { Substitute, Arg } = require('@fluffy-spoon/substitute') - -const notFound = reply => reply.code(404).send({ error: 'not found' }) - -const reply = Substitute.for() -reply.code(Arg.all()).returns(reply) -notFound(reply) -reply.received(1).code(404) -reply.received(1).send({ error: 'not found' }) -``` - -The message names up to three such places, the nearest first (`... on substitutes further down: @Substitute.where(0).first(...), @Substitute.where(1).first(...), @Substitute.where(2).first(...) and more.`), each cut after 1,000 characters, and what to do about the first of them. When every step from the checked substitute down to it is a call, the line names a setup for each method on the way, from the top, each method once: `sub.code(Arg.all()).returns(sub)` for `reply.code(404).send(...)` above, `sub.code(Arg.all()).returns(sub) and sub.header(Arg.all()).returns(sub)` for `reply.code(404).header('content-type', 'application/json').send(...)` (see below), `sub(Arg.all()).returns(sub) and sub.where(Arg.all()).returns(sub)` for a knex-style function substitute (`db('users').where('id', 1).first()`), and `sub.logger.child(Arg.all()).returns(sub.logger)` for a check of the auto-substitute `app.logger`. With more than three methods on the way, it names three and adds `and likewise for the 2 other methods on the way`. When a step on the way reads a property instead of calling a method, or is a call with matchers whose substitute a nested setup shares, there is nothing to configure, and the line says which substitute to check, by its whole path: `info was not called on @Substitute itself, but on a substitute further down: @Substitute.logger.info(...). To check calls there, check that substitute: sub.logger.received(1).info(...)` for `app.logger.info('started')` checked as `app.received(1).info('started')`, and `sub.users.where({ id: 1 }).limit(1).received(1).exec(...)` for `db.users.where({ id: 1 }).limit(1).exec()` checked as `db.received(1).exec()`. - -Both remedies are written as code that does what they say, where their arguments allow it (see below): `sub` stands for the checked substitute, and the path is written in full, as JavaScript writes the members, `sub['my-key']`, `sub[0]`, `sub[Symbol.for('k')]` for a symbol registered with `Symbol.for()` and `sub[Symbol.iterator]` for a well-known one (the place named before the remedy is printed as messages print paths, `@Substitute.my-key.x(1).run(...)`, and shortened when it is long). A substitute that a setup with matchers shares is written as the concrete call that it was returned to: after `reply.code(Arg.any()).send(Arg.all()).returns(true)` and the code's `reply.code(404).send(1)`, `check that substitute: sub.code(404).received(1).send(...)`; and after `io.to(Arg.any()).emit(Arg.all()).returns(true)` and the code's `io.to('room-a').compress(true).emit('m')`, checked as `io.to('room-a').received(1).emit('m')`, `make the method return the substitute (sub.to('room-a').compress(Arg.all()).returns(sub.to('room-a')))`. When it was returned to several calls, the fluent remedy names the first of them, which works for all, as every matching call answers the same substitute, and the check remedy names the call with matchers, as a check through one of the concrete calls would be a usage error (see [Through a call with matchers](#through-a-call-with-matchers)). The check remedy writes its path as code only when every argument on it prints as code that gives an equal value: primitives other than symbols (numbers, also `NaN`, `-0` and `Infinity`, bigints such as `10n`, strings of up to 100 characters, booleans, `null` and `undefined`), and plain arrays and objects printed in full, with up to 10 items or keys, string keys and plain values only, each of them such a primitive or an empty array or object (`sub.users.where({ id: 1 }, 'a', 2n).limit(1).received(1).exec(...)`). Otherwise the line names the substitute as messages print it, and says how to reach it: `To check calls there, check that substitute, @Substitute.users.where(1970-01-01T00:00:00.000Z), reached with the same arguments, with received(1) on it; its arguments cannot be written as code.` That is so for `Date`s, `Map`s, `Set`s, class instances, functions, substitutes, symbols, `Buffer`s and typed arrays, URLs, errors, regular expressions, objects without a prototype, objects and arrays nested in an argument (`{ a: { b: 1 } }`, `[1, [2]]`), longer strings, and matchers: after two hand-outs of a shared substitute, the line says `check that substitute, @Substitute.code(Arg.any{any}), reached with the same arguments, with received(1) on it`, which is `sub.code(Arg.any()).received(1).send(1)`. The fluent remedy writes the arguments of its path as messages print them, so those that do not print as code need to be written by hand there: functions (`[Function: onSaved]`), long values that are cut, and matchers. Following a remedy whose value is a call (`returns(sub.to('room-a'))`) makes that call, which is recorded, as the value of any setup is. A path that cannot be written as code, because a member on the way has a symbol that is not registered with `Symbol.for()` or because it would be longer than 1,000 characters, is not given: the line then says `To check calls there, check that substitute itself, with received(1) on it; its path cannot be written as code (a symbol that is not registered with Symbol.for(), or more than 1000 characters).`, or `For a fluent API, make the method return the substitute it is called on (a setup with Arg.all() whose value is that substitute) or mimick an instance whose methods return this.` A check [through a call with matchers](#through-a-call-with-matchers) looks below the substitutes that it counts. The line is added only to a check that fails, and only when the checked substitute has no record of the member (no read, call or assignment), the member was called (not only read) further down, and the check expects calls (not `didNotReceive()` or `received(0)`, which pass then anyway). It is not added to checks of assignments, or of calls of the substitute itself. To find these places, the library looks through all the auto-substitutes, breadth first, however far down they are; checks that pass look for nothing. - -```js -const { Substitute } = require('@fluffy-spoon/substitute') - -// the code under test sets a header on the way -const notFound = reply => reply.code(404).header('content-type', 'application/json').send({ error: 'not found' }) - -const reply = Substitute.for() -notFound(reply) -reply.received(1).send({ error: 'not found' }) // throws SubstituteException -``` - - -```text -SubstituteException: Call count mismatch in @Substitute.send: -Expected to receive 1 property read or method call matching send, but received none. -send was not called on @Substitute itself, but on a substitute further down: @Substitute.code(404).header('content-type', 'application/json').send(...). A call that is not configured answers a new substitute. For a fluent API, make each method on the way return the substitute (sub.code(Arg.all()).returns(sub) and sub.header(Arg.all()).returns(sub)) or mimick an instance whose methods return this. -``` - -Following the line makes the check pass, and so does the check that the line names when a property is read on the way: - -```js -const { Substitute, Arg } = require('@fluffy-spoon/substitute') - -const notFound = reply => reply.code(404).header('content-type', 'application/json').send({ error: 'not found' }) - -const reply = Substitute.for() -reply.code(Arg.all()).returns(reply) -reply.header(Arg.all()).returns(reply) -notFound(reply) -reply.received(1).send({ error: 'not found' }) - -// the code under test reads db.users on the way -const db = Substitute.for() -db.users.where({ id: 1 }).limit(1).exec() -db.received(1).exec() // throws SubstituteException: To check calls there, check that substitute: sub.users.where({ id: 1 }).limit(1).received(1).exec(...) -db.users.where({ id: 1 }).limit(1).received(1).exec() - -// a path with an argument that does not print as code is named as messages print it -const reports = Substitute.for() -const since = new Date(0) -reports.users.where(since).exec() -reports.received(1).exec() // throws SubstituteException: check that substitute, @Substitute.users.where(1970-01-01T00:00:00.000Z), reached with the same arguments, with received(1) on it; its arguments cannot be written as code. -reports.users.where(since).received(1).exec() - -// a member whose name is not an identifier is written in brackets -const cache = Substitute.for() -cache['user-1'].touch(1).save() -cache.received(1).save() // throws SubstituteException: To check calls there, check that substitute: sub['user-1'].touch(1).received(1).save(...) -cache['user-1'].touch(1).received(1).save() -``` - -## Through a call with matchers -A call with a [matcher](#argument-matchers), like `repo.find(Arg.any())`, stands for every call that it matches. A setup through it configures what those calls give: after `repo.find(Arg.any()).name.returns('ann')`, `repo.find(5).name` is `'ann'`. A check through it checks the substitutes that the matching calls returned, so `bus.on('saved', Arg.any()).received(1)()` checks that the function that a received `bus.on('saved', ...)` call returned was called once: - -* It counts the calls of every substitute that a received call matching the call with matchers returned: its auto-substitute, or the substitute that a setup made it return (also through a matcher setup, a nested setup through a call with matchers, or a mimicked instance, including the substitute itself for a fluent method), also a substitute of another copy of the package (see below). They count together, so after `app.repo('users').save(1)` and `app.repo('orders').save(1)`, `app.repo(Arg.any()).received(2).save(1)` passes. When no received call matches, the check counts no calls: `bus.on('deleted', Arg.any()).received(1)()` fails with "received none", and `didNotReceive()` passes. -* It works with every form of check, `received()`, `received(count)`, `didNotReceive()` and the symbols, and further down, step by step, as at the first step: `app.db(Arg.any()).table(Arg.any())[received](2).insert(Arg.any())`, `repo.find(Arg.any()).items[received](1).clear()` (the `clear()` calls of the `items` of each matching result), also when a setup with the same matchers returns a substitute (`api.client(Arg.any()).returns(client)`, then `api.client(Arg.any()).items[received](1).clear()`) or configures a member further down (`app.repo(Arg.any()).db.returns(db)`, then `app.repo(Arg.any()).db[received](2).query(Arg.any())`), and in the `configure` view, `repo[configure]().find(Arg.any())[received](1).save(1)`. It works for function substitutes (`factory(Arg.any())[received](1).start()`) and for `new` (`ns.Client(Arg.any())[received](1).connect()`), too. The string forms `received(count)` and `didNotReceive()` follow the rules of [In JavaScript](#in-javascript) there: called and followed by a member, they are a check; followed by `.returns()` or another setup method, or not called, they configure a member of your own called `received`, as in `inbox.folder(Arg.any()).received(1).returns(['mail'])`; and in the `configure` view, they are always setups. -* Calls that the code under test made through `call` or `apply` count under both of their meanings (see [`call`, `apply` and `bind`](#call-apply-and-bind)): after `client.rpc.call('getUser', 1).save()`, both `client.rpc.call('getUser', Arg.any())[received](1).save()` and `client.rpc(Arg.any())[received](1).save()` pass, and with `api.getUser(1).returns(user)`, `api.getUser(Arg.any())[received](1).save()` counts the `save()` calls on `user` that a wrapper made through `fn.apply(this, args)`. -* The failure message names the check by its whole path, such as `@Substitute.client(Arg.any{any}).items.clear`, and lists each call with the substitute that received it, as below. -* A check changes nothing: it is not a setup, so the calls that it matches keep returning the same auto-substitutes, and the setups made on them keep answering. Neither does a read through a call with matchers that configures nothing (`repo.find(Arg.any()).name` as a statement). -* A substitute that a setup through the call with matchers returns, as in `api.client(Arg.any()).returns(client)`, is checked through the calls that returned it, at every step: `api.client(Arg.any())[received](1).get(1)` and `api.client(Arg.any()).items[received](1).clear()` count the calls of `client` only when a received `api.client(...)` call returned `client`, and then all of them, also those made on `client` from elsewhere. Only setups through the call with matchers go to `client`; checks never count `client` alone. Check `client` itself (`client.received(1).get(1)`) when the code under test may have it from elsewhere. -* A received call that the check matches, but that a setup answered with a value that is not a substitute, makes the check a usage error, a `SubstituteException` that names that call and what answered it (see the last example below): a value of `returns()` (also `returns()` without a value), a promise of `resolves()` or `rejects()`, an error of `throws()`, a function that `.bind()` made from a substitute (`returns(worker.process.bind(worker))`, also from a substitute of another copy of the package, see below), a result of `mimicks()` or of a mimicked method that is not a substitute (or a mimicked method that threw, or a getter of a mimicked instance that threw when the code under test read the member), and a revoked proxy (`Proxy.revocable()`, of a function or an object), which the message names as ``. The calls that the code under test made on such a value, or on a substitute that it holds or resolves to, cannot be counted through the call with matchers, so the check would pass where it must not. Check the value directly instead (`user.received(1).save()` for a substitute `user` that a promise resolved to, and the member that a function is bound from, `worker.received(1).process(1)`), or check a concrete call. This holds for every form and count of the check, `didNotReceive()` too, at every step, and however the code under test made the call: directly, through a stored reference, through `call`, `apply` or `bind`, or with `new`. It holds for a member read on the way, too: after `api.session('s1').user.resolves(user)`, `api.session(Arg.any()).user[didNotReceive]().save()` is a usage error that names the read `@Substitute.session('s1').user`, and after `api.session('s1')[mimick]({ get user() { throw failure } })` and the code's read of `api.session('s1').user` (which throws `failure`, as the getter does), `api.session(Arg.any()).user.received(1).save()` is a usage error that says that the read `threw an error instead of answering a substitute`. The message names a call or read on a substitute that a setup with matchers shares by the concrete call that the substitute was returned to, as the lists of calls do (see below): `the read of @Substitute.session('s1').user` after `api.session(Arg.any()).user.returns(5)`. The symbol forms throw when the check is made (`api.load(Arg.any())[didNotReceive]()`), and the string forms when it is used (`api.load(Arg.any()).didNotReceive().save()`), because `api.load(Arg.any()).received(1).returns(x)` is still a setup of a member called `received`. Only the received calls and reads that match decide, by what they answered when they were made: after `api.load(1).returns(user)` and `api.load(2).returns(7)`, `api.load(Arg.is(id => id === 1))[received](1).save()` counts the calls of `user`, and when no received call matches, the check counts none, whatever the setups answer. Configuring a member again after the code under test used it changes nothing that a check counts, and of a sequence such as `returns(first, second)`, only the values that were handed out count. -* A substitute of another copy of the package (see [The symbol API](#the-symbol-api)) that a matching received call answered is counted, too. A function bound from it (`returns(worker.process.bind(worker))`, with `worker` of the other copy) is not: it is a value that is not a substitute, as above, and makes the check a usage error, in every form. The copies note their bound functions in the object that they share, so a copy of an earlier version, which does not, may still take a function bound from one of its substitutes for its substitute, and make the check itself. If it is the only substitute that the check counts, and the check is opened on it (`factory.create(Arg.any())[received](1).run()`, where `create()` answered it), the check is made by that copy, so its failure message comes from there, and names the calls by that substitute's own path (`@Substitute.run`). When the check goes on below it (`factory.create(Arg.any()).task('q')[received](1).run()`), only that copy knows what the calls and reads below it answered, so the check is a usage error that says so: check that substitute directly, with its own copy's check (`job.task('q').received(1).run()`). If there are other substitutes as well, its calls cannot be counted together with theirs, and the check is a usage error, too; check each of those substitutes directly then. When the other copy makes the check, this copy does not see it, so the reads and calls of the test's own expression that lead to it stay recorded: after `factory.create('b')[didNotReceive]().run()`, where `create()` answers a substitute of the other copy, `factory.received(1).create('b')` passes although the code under test never called `create('b')`. Check such a call before you check through it, or check the substitute of the other copy directly. -* Not counted, when an argument object of a received call was changed after the call: possibly the auto-substitute of that call (see [How arguments are compared](#how-arguments-are-compared); passing the same object always works). - -```js -const { Substitute, Arg, received, didNotReceive } = require('@fluffy-spoon/substitute') - -// the code under test subscribes with a handler of its own, and unsubscribes later -const bus = Substitute.for() -const unsubscribe = bus.on('saved', () => { }) -unsubscribe() - -bus.on('saved', Arg.any()).received(1)() -bus.on('saved', Arg.any())[received](1)() -bus.on('saved', Arg.any()).didNotReceive()() // throws SubstituteException: Expected to receive 0 method calls matching @Substitute.on('saved', Arg.any{any})(), but received 1. -bus.on('deleted', Arg.any()).received(1)() // throws SubstituteException: Expected to receive 1 method call matching @Substitute.on('deleted', Arg.any{any})(), but received none. - -// a check changes nothing: find(1) keeps its auto-substitute, and its setup keeps answering -const repo = Substitute.for() -const user = repo.find(1) -user.name.returns('ann') -repo.find(Arg.any())[didNotReceive]().delete() -console.log(repo.find(1) === user) // prints true -console.log(repo.find(1).name) // prints ann - -// a nested setup through a call with matchers -repo.find(Arg.any()).email.returns('ann@example.com') -console.log(repo.find(7).email) // prints ann@example.com -``` - -```js -const { Substitute, Arg } = require('@fluffy-spoon/substitute') - -const app = Substitute.for() -// the code under test -app.repo('users').save(1) -app.repo('orders').save(2) - -app.repo(Arg.any()).received(1).save(Arg.any()) // throws SubstituteException -``` - - -```text -SubstituteException: Call count mismatch in @Substitute.repo(Arg.any{any}).save: -Expected to receive 1 method call matching save(Arg.any{any}), but received 2. -All property or method calls to @Substitute.repo(Arg.any{any}).save received so far: -› ✔ @Substitute.repo('users').save(1) - called at Object. (test/app.test.js:5:19) -› ✔ @Substitute.repo('orders').save(2) - called at Object. (test/app.test.js:6:20) -``` - -Two steps down, with a setup that returns a substitute of your own: - -```js -const { Substitute, Arg, received, didNotReceive } = require('@fluffy-spoon/substitute') - -const api = Substitute.for() -const client = Substitute.for() -api.client(Arg.any()).returns(client) - -// the code under test has the client from elsewhere -client.items.clear() -// no received api.client(...) call returned client, so its calls do not count here -api.client(Arg.any()).items[didNotReceive]().clear() -api.client(Arg.any()).items[received](1).clear() // throws SubstituteException: Call count mismatch in @Substitute.client(Arg.any{any}).items.clear - -// the code under test gets the client through api.client() -api.client('users') -api.client(Arg.any()).items[received](1).clear() -client.items.received(1).clear() -``` - -A received call that a setup answered with a promise, which is not a substitute: - -```js -const { Substitute, Arg, didNotReceive } = require('@fluffy-spoon/substitute') - -const api = Substitute.for() -const user = Substitute.for() -api.load(Arg.any()).resolves(user) - -// the code under test -api.load(1).then(loaded => loaded.save()).then(() => user.received(1).save()) - -api.load(Arg.any())[didNotReceive]().save() // throws SubstituteException -``` - - -```text -SubstituteException: Cannot check through @Substitute.load(Arg.any{any}): the received call @Substitute.load(1), which it matches, is configured with resolves(@Substitute), so it answered a promise, which is not a substitute. A check through a call with matchers counts the calls of the substitutes that the matching calls answered, and the calls made on that value are not recorded there. Check that value directly instead (for example user.received(1).save(), for a substitute user that it holds or resolves to), or check a concrete call. -``` - -In TypeScript, the result of a call is typed as the member's value with the setup API, without the check views (see [Typing limitations](#typing-limitations)), so a check through a call with matchers needs a cast through `unknown` to a substitute of the value's type. A cast without `unknown` does not compile (TS2352, "Conversion of type ... may be a mistake"). After the cast, the arguments of the check are type-checked as usual: - -```typescript -import { Substitute, Arg, SubstituteOf, didNotReceive } from '@fluffy-spoon/substitute' - -interface Repo { save(id: number): void } -interface App { repo(name: string): Repo } - -const app = Substitute.for() -// the code under test -app.repo('users').save(1) - -;(app.repo(Arg.any()) as unknown as SubstituteOf).received(1).save(1) -;(app.repo(Arg.any()) as unknown as SubstituteOf)[didNotReceive]().save(2) -// @ts-expect-error without the cast, the call's result has no check views -app.repo(Arg.any()).received(1).save(1) -// @ts-expect-error after the cast, save() takes a number -;(app.repo(Arg.any()) as unknown as SubstituteOf)[didNotReceive]().save('1') -``` - -The cast is the same after a setup that returns a substitute of your own (`app.repo(Arg.any()).returns(repo)`), and for a value that is a function: `(bus.on('saved', Arg.any()) as unknown as SubstituteOf<() => void>).received(1)()`. - -**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')` and `io.to('room-b')` return one substitute, which holds the setup of `emit()`. A setup with matchers that returns a substitute of your own (`io.to(Arg.any()).returns(room)`) and a mimicked instance whose method returns one substitute do the same. So the calls that the code under test makes on what `io.to('room-a')` returned are calls of what `io.to('room-b')` returns, too. A check written through a concrete call, such as `io.to('room-b').received(1).emit('message', Arg.any())` or `db('users').received(1).where('id', 1)`, therefore decides from the received calls that the shared substitute was returned to: - -* When every one of them matches the concrete call (the code under test called only `io.to('room-b')`), the check counts the calls of the substitute, as any check does. -* When none of them matches (the code under test called only `io.to('room-a')`), nothing came through the concrete call, so the check counts none: `received(1)` fails with "received none" and lists the substitute's calls with a ✘, and `didNotReceive()` passes. -* When some of them match and some do not, which of the substitute's calls came through the concrete call cannot be told apart, and the check is a usage error, a `SubstituteException` that names the call, the setup that shares the substitute, up to three of the other calls that it was returned to (then `and N more`), and what to do instead (see the second example below): check the call itself (`io.received(1).to('room-b')`), configure the concrete calls so that each answers a substitute of its own (`io[configure]().to('room-b').returns(roomB)`), or check through the call with matchers, which counts the calls that came through every call that it matches (`io.to(Arg.any()).received(2).emit('message', Arg.any())`). - -This holds for every form of the check, at every step of a route (`db('users').where(Arg.all())[received](1).first()`), for calls that the code under test made through `call`, `apply` or `bind`, and for checks written through them: after `rpc.call('getUser', Arg.any()).returns(user)` and the code's `rpc.call('getUser', 1).save()`, `rpc.call('getUser', 2).received(1).save()` fails with "received none", and so do `io.to.call(io, 'room-b').received(1).emit(...)` and `io.to.apply(io, ['room-b'])[received](1).emit(...)` after only room-a was used. A concrete call with a setup of its own answers with its own value, so a check through it counts as usual. - -A route that comes back to the same substitute is matched step by step, too: a query builder whose methods return the builder (knex-style, `query.where(Arg.all()).returns(query)`), socket.io's broadcast operator, whose `to()` returns the operator itself (`operator.to(Arg.any()).returns(operator)`), fastify's `reply.code(...).header(...)`, and a cycle such as `io.to('b').back(1).to('a')`. The substitute notes each time that the expression hands it out, so each step of the check is matched with the step of the code under test that it stands for, and the rule above applies at each step: after the code's `db('users').where('id', 1).first()`, `db('orders').where('id', 1).received(1).first()` fails with "received none", `db('orders').where('id', 1).didNotReceive().first()` passes, and so do `db('users').where('id', 1).received(1).first()` and the check of the builder itself, `query.received(1).first()`. The same holds for a setup without matchers that answers the substitute that it is called on (`query.where('id', 1).returns(query)`) below a shared step. When the expression handed the builder out to steps with different arguments, as `db('users').where('id', 1).where('name', 'x').first()` does, a check through one of those steps is the usage error above, also when it follows the whole route (`db('users').where('id', 1).where('name', 'x').received(1).first()`), as which of the builder's calls came after which step cannot be told apart; a check through another first step (`db('orders')`) still fails with "received none". Check the builder itself (`query.received(1).first()`), or through the calls with matchers (`db('users').where(Arg.all()).where(Arg.all()).received(1).first()`). A check follows the route in this way also when another expression hands the same substitute out while the code under test goes through the route, for example in a `mimicks()` function on the way. A check never counts only the lower part of such a route. - -```js -const { Substitute, Arg } = require('@fluffy-spoon/substitute') - -// a knex-style query builder: db(table) answers it, and where() returns the builder itself -const db = Substitute.for() -const query = Substitute.for() -db(Arg.any()).returns(query) -query.where(Arg.all()).returns(query) -// the code under test -db('users').where('id', 1).first() - -db('users').where('id', 1).received(1).first() -db('orders').where('id', 1).didNotReceive().first() -query.received(1).first() -db('orders').where('id', 1).received(1).first() // throws SubstituteException: but received none - -// two where() steps with different arguments -const reports = Substitute.for() -const reportQuery = Substitute.for() -reports(Arg.any()).returns(reportQuery) -reportQuery.where(Arg.all()).returns(reportQuery) -reports('users').where('id', 1).where('name', 'x').first() -reportQuery.received(1).first() -reports('users').where(Arg.all()).where(Arg.all()).received(1).first() -reports('users').where('id', 1).where('name', 'x').received(1).first() // throws SubstituteException: cannot be told apart -``` - -A [clear](#clearing-received-calls) of the substitute that the route starts from bounds the check, too: after `io[clearReceivedCalls]()`, the calls that a shared substitute received through hand-outs made before the clear do not count through `io`'s route: neither as calls that came through the concrete call, nor as calls that came through other calls (which would make the check a usage error). So after `io.to(Arg.any()).returns(room)`, the code's `io.to('room-a').emit('welcome')`, `io[clearReceivedCalls]()` and `io.to('room-b').emit('bye')`, `io.to('room-b').received(1).emit('welcome')` fails with "received none" (the list shows `emit('bye')`), and `io.to('room-b').didNotReceive().emit('welcome')` passes. A check of `room` itself still counts the call, `room.received(1).emit('welcome')`, as `room`'s own calls are cleared only by `room[clearReceivedCalls]()`. This holds for every form of the check, for checks through a call with matchers (`io.to(Arg.any()).received(1).emit(Arg.any())` counts only `emit('bye')`), and for a clear of a substitute further up a longer route, or in the middle of it. - -A setup with matchers can also answer with the substitute that it is called on, as a fluent method does: `io.to(Arg.any()).returns(io)`, a mimicked instance whose `to()` returns `this`, or the fluent remedy of a failure message (see [Fluent interfaces](#fluent-interfaces)). Then `io.to('room-b')` is `io` itself, and a check through it narrows in the same way only when the check is written on the same line, after the call: after `io.to('room-a').emit('m')`, `io.to('room-b').received(1).emit('m')` fails with "received none", `io.to('room-a').received(1).emit('m')` passes, and neither records its call of `to()`. A check on a later line, or a chain broken over several lines as code formatters such as prettier write long ones, is a check of `io` itself: it counts every `emit()` call of `io`, so `received(1)` passes there for room-b too, and its call of `to('room-b')` is recorded. Write such a check on one line, or check the call itself (`io.received(1).to('room-b')`). The rule is the line, not the statement (the line of the source, also in transpiled test files that have a source map; see [Which calls lead to a setup or a check](#which-calls-lead-to-a-setup-or-a-check)), so two statements written on one line count as one expression there, and a setup on the same line through such a call (`map.set('b', 2).get(Arg.any()).returns(5)` after `map.set(Arg.all()).returns(map)`) leaves the call out as well (see [Which calls lead to a setup or a check](#which-calls-lead-to-a-setup-or-a-check)). - -```js -const { Substitute, Arg } = require('@fluffy-spoon/substitute') - -// a fluent to(), set up to return the substitute itself -const io = Substitute.for() -io.to(Arg.any()).returns(io) -// the code under test -io.to('room-a').emit('message', 'hi') - -io.to('room-a').received(1).emit('message', 'hi') -io.to('room-b').received(1).emit('message', 'hi') // throws SubstituteException: but received none -// the checks' own calls of to() are not recorded -io.received(1).to('room-a') -io.didNotReceive().to('room-b') -``` - -The check decides so only when it is opened in the same expression as the concrete call (see [Which calls lead to a setup or a check](#which-calls-lead-to-a-setup-or-a-check)). That includes a check that a helper of your own opens and returns for its caller to complete (`const sentTo = (io, room) => io.to(room).received(1)`, then `sentTo(io, 'room-b').emit('message', Arg.any())`), an IIFE, and a check view that you store and complete later. But a handle of the concrete call that you store (`const roomB = io.to('room-b')`) and check later, after other uses of substitutes, counts every call of the shared substitute, and so does a handle that you pass to a helper that opens the check (`const open = view => view.received(1)`, then `open(io.to('room-b')).emit(...)`). A check view of the string forms (`received()`, `didNotReceive()`) that is used a second time is decided by where that use is made, which is not the expression that opened it, so the check counts every call of the shared substitute: after `const view = io.to('room-b').didNotReceive()`, the first `view.emit('m')` passes, and a second one fails, as it counts room-a's `emit()`. Open a new check for each use, or use the symbol forms, whose views keep their route. A check through a concrete call whose shared substitute belongs to another copy of the package counts every call of that substitute, too, because that copy makes the check (see above). So does a concrete check that an `Arg.is()` predicate makes on a substitute that it looks at (see [Matching specific arguments](#matching-specific-arguments)): in the predicate of a check, and in the predicate of a setup when the call of the code under test that is compared with it passes that substitute (`io`, or the shared substitute itself). Make such checks outside the predicate. - -Failure messages, the usage errors of checks through a call with matchers, and printouts show the calls of such a substitute with the call that it was returned to, `@Substitute.to('room-a').emit('message', { text: 'hi' })`, when there is one such call, or several with equal arguments. When it was returned to calls with different arguments, its calls keep the label of the call with matchers (`@Substitute.to(Arg.any{any}).emit('message', 1)`), and a failure message adds a line under the list of calls: `@Substitute.to(Arg.any{any}) is shared by every call matching it; it was returned to @Substitute.to('room-a') and @Substitute.to('room-b').` (up to three calls, then `and N more`). The first line of a message, the setups of a printout and the path of the shared substitute itself (`String(io.to('x'))` starts with `@Substitute.to(Arg.any{any}) {`) keep the matchers. - -```js -const { Substitute, Arg, received } = require('@fluffy-spoon/substitute') - -const io = Substitute.for() -io.to(Arg.any()).emit(Arg.all()).returns(true) - -// the code under test sends the message to another room than the test expects -io.to('room-a').emit('message', { text: 'hi' }) - -io.to('room-a').received(1).emit('message', { text: 'hi' }) -io.to('room-b').didNotReceive().emit('message', Arg.any()) -io.to('room-b').received(1).emit('message', { text: 'hi' }) // throws SubstituteException: Expected to receive 1 property read or method call matching emit, but received none. -io.received(1).to('room-a') -// String(io) lists the received call as to('room-a').emit('message', { text: 'hi' }) -console.log(String(io).includes("to('room-a').emit('message', { text: 'hi' })")) // prints true -console.log(io.to('room-a') === io.to('room-b')) // prints true - -// a knex-style query builder: db(table).where(...).first() -const db = Substitute.for() -db(Arg.any()).where(Arg.all()).first().resolves({ id: 1 }) -// the code under test queries the orders -db('orders').where('id', 1).first() - -db('orders').received(1).where('id', 1) -db('users').where(Arg.all())[received](0).first() -db('users').received(1).where('id', 1) // throws SubstituteException -``` - - -```text -SubstituteException: Call count mismatch in @Substitute('users').where: -Expected to receive 1 property read or method call matching where, but received none. -All property or method calls to @Substitute('users').where received so far: -› ✘ @Substitute('orders').where('id', 1) - called at Object. (test/db.test.js:23:16) -``` - -When the shared substitute was returned to more than one room: - -```js -const { Substitute, Arg } = require('@fluffy-spoon/substitute') - -const io = Substitute.for() -io.to(Arg.any()).emit(Arg.all()).returns(true) -// the code under test -io.to('room-a').emit('message', 1) -io.to('room-b').emit('message', 2) - -io.to(Arg.any()).received(2).emit('message', Arg.any()) -io.received(1).to('room-b') -io.to(Arg.any()).received(3).emit('message', Arg.any()) // throws SubstituteException: @Substitute.to(Arg.any{any}) is shared by every call matching it; it was returned to @Substitute.to('room-a') and @Substitute.to('room-b'). -io.to('room-b').received(1).emit('message', 2) // throws SubstituteException -``` - - -```text -SubstituteException: Cannot check through @Substitute.to('room-b'): @Substitute.to('room-b') has no setup of its own, so it answered the substitute @Substitute.to(Arg.any{any}), which the setup @Substitute.to(Arg.any{any}) gives every call that it matches, and that substitute was also returned to @Substitute.to('room-a'). Which of its calls came through @Substitute.to('room-b') cannot be told apart. Check the call itself instead (sub.received(1).to('room-b')), configure the concrete calls so that each answers a substitute of its own, or check through the call with matchers, which counts the calls that came through every call it matches (sub.to(Arg.any{any}).received(n)...). -``` - -## Which calls lead to a setup or a check -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 part of that setup or check, so they are not recorded as received calls. A value that the code under test got from a substitute keeps the call that returned it, though, so you can configure or check that value and still verify how the code under test got it: - -```js -const { Substitute } = require('@fluffy-spoon/substitute') - -// the code under test -function openConnection(driver) { - return driver.connect('db://test') -} - -const driver = Substitute.for() -const connection = openConnection(driver) -connection.isOpen.returns(true) - -console.log(connection.isOpen) // prints true -driver.received(1).connect('db://test') -driver.didNotReceive().connect('db://test') // throws SubstituteException -``` - -The library tells the two apart by where they happen: the reads and calls before a setup or a check are left out only when they were made in the same file and the same function as the setup or check. (It compares the first stack frame outside the library: the position of the enclosing function, or on Node.js before 14.18 its name.) A call is made where it is invoked, which is not always where the method was read. So: - -* A chain written over several lines, or in a helper function of your own, is one setup or check. So is a check that a helper opens and returns for its caller to complete, such as `const sentTo = (io, room) => io.to(room).received(1)` or `const loggerCheck = app => app.logger.received(1)` in your test utilities: the reads and calls in the expression that opens the check (with `received()`, `didNotReceive()`, `[received]()` or `[didNotReceive]()`) belong to the check wherever it is completed, in the caller of the helper, after an IIFE, or in a later statement or callback. So `sentTo(io, 'room-b').emit('message', Arg.any())` records no call of `to('room-b')`, and after `const later = service.logger.received(1)`, `t.notThrows(() => later.info('x'))` records no read of `logger`. -* A handle that you store and use in the same function is part of the setup: after `const logger = app.logger` and `logger.level.returns(3)`, the read of `app.logger` is not recorded. The same holds for a method that you read and then call in that function (`const load = app.load` and `load(1).size.returns(3)`). -* A member or call configured to return another substitute counts like an auto-substitute: after `app.getCalculator().returns(calculator)`, the setup `app.getCalculator().add(1, 2).returns(3)` records no call of `getCalculator()`, and after `app.logger.returns(logger)`, the check `app.logger.received(1).info('started')` records no read of `logger`. Reads and calls by the code under test are kept. As with a stored handle, a test that calls `app.getCalculator()` itself and then, in the same function, starts a setup or check from `calculator` with its next use of a substitute leaves that call out. When the configured value is the substitute itself (`map.set(Arg.all()).returns(map)`, a fluent `return this`), nothing is left out: after `map.set('b', 2)` in a test, `map.received(1).set('b', 2)` on the next line passes. Only an operation on the same line, after such a call, continues it: `map.set('b', 2).get(Arg.any()).returns(5)` is one setup, which records no call of `set()`, and so is a check through such a call on one line (see [Through a call with matchers](#through-a-call-with-matchers)). Two statements written on one line count as one expression here. The line is the source's, also in transpiled test files (see below). A member read on such a line and called on a later one is decided where it is called, as a call is made where it is invoked (see below): after `const get = map.set('k', 1).get` and, on the next line, `get('x').returns(5)`, `map.get('x')` answers 5 and `map.received(1).set('k', 1)` passes. -* A handle that you get in one function and use in another one keeps the reads that produced it. For example, after `const click = app.handlers.click` in a test, `t.notThrows(() => click.received(1).fire())` opens the check in a callback, so the reads of `handlers` and `click` stay recorded, and `app.didNotReceive().handlers` would fail. The same holds for a handle that you pass to a helper that opens the check: with `const open = view => view.received(1)`, `open(api.getUser(1)).save()` keeps the call of `getUser(1)`. -* Calls that the code under test makes in its own functions are kept. That includes calls through a method that the test hands to it, like `new UserService(api.getUser)` or `openWith(driver.connect)`: the call is made where the code under test invokes the method, and its `called at` line in failure messages names that place, not the line of the test that read `api.getUser`. (For a direct call like `api.getUser(1)`, the read and the call are the same place.) This holds also when the code under test invokes the method with the substitute as `this`, like `Reflect.apply(this.fetch, this.client, [id])`, `fetch.call(api, id)` or a wrapper such as `(...args) => Reflect.apply(method, client, args)`: whether a read and a call belong to one expression depends on where they happen, as described here, and `this` plays no part. -* `Reflect.apply()` and a function's `call`, `apply` and `bind` have no stack frame of their own, so in a test, `Reflect.apply(app.getUser, app, [2]).name.returns('bob')` is one setup, like `app.getUser(2).name.returns('bob')`. A method that a built-in function calls itself, like `getUser` in `[1, 2].map(api.getUser)`, is called by that function, not by the test: those calls are kept, also when the test then configures their results, and their `called at` line reads `called at Array.map ()`. (`map` passes the index and the array as well, so these calls are `getUser(1, 0, [1, 2])` and `getUser(2, 1, [1, 2])`.) -* Calls that the code under test makes from a promise job, like `Promise.resolve(id).then(getUser)`, are kept too. Such a call has no stack frame outside the library (the library ignores the `async` frames that V8 adds for the functions awaiting the promise), and a call without a frame is never part of a setup or check that has one. -* Only when neither the call nor the setup or check has a stack frame outside the library does position alone decide: a setup or check right after the call that returned its value, with no other use of a substitute in between, leaves that call out. That happens when V8 collects no stack frames, as with `Error.stackTraceLimit = 0` or a limit that V8 cannot use, and when the library cannot read them because `Error.prepareStackTrace` cannot be replaced for a moment, for example when `Error` is frozen (see below). - -**Lines in transpiled test files.** Two rules compare lines: a step on a substitute that a call on that same substitute handed out continues the call's expression only on the same line, after the call (above, and in [Through a call with matchers](#through-a-call-with-matchers)), and a matcher that throws on the line where a check reads its member, after it, cancels that check's later report (see [Assertions that fail later](#assertions-that-fail-later)). Both compare the lines of the source wherever Node.js has a source map for the file that runs: with tsx (`node --import tsx`, `node --require tsx/cjs`, also for `.mts` files), which writes each file on one line, with `node --enable-source-maps` and a map, and with anything else that registers its maps with Node.js. Node.js' own type stripping keeps the lines, and so do vitest and jest (with `babel-jest` or `ts-jest`), which run code whose lines are the source's. Without a map, the lines of the code that runs decide. So in minified or bundled test code without a source map, or with a map that Node.js does not use (without `--enable-source-maps`), statements that were put on one line count as one expression: after `map.set(Arg.all()).returns(map)` and the code's `map.set('b', 2)`, `map.didNotReceive().set('b', 2)` on the next line of the source passes, and a matcher that throws in a later statement cancels the later report of a check. Run such tests from the source, or with their source maps. The other rules of this section compare the file and the function that a read or call is made in, which stay apart on one line, too. - -```js -const { Substitute } = require('@fluffy-spoon/substitute') - -// the code under test calls the function that it is given -class UserService { - constructor(fetchUser) { - this.fetchUser = fetchUser - } - - load(id) { - return this.fetchUser(id) - } -} - -const api = Substitute.for() -const user = new UserService(api.getUser).load(1) -user.name.returns('ann') - -console.log(user.name) // prints ann -api.received(1).getUser(1) -api.didNotReceive().getUser(1) // throws SubstituteException -``` - -```js -const { Substitute, Arg } = require('@fluffy-spoon/substitute') - -// the code under test calls the method with the client as `this` -class Loader { - constructor(client, fetch) { - this.client = client - this.fetch = fetch - } - - load(id) { - return Reflect.apply(this.fetch, this.client, [id]) - } -} - -const api = Substitute.for() -const user = new Loader(api, api.getUser).load(1) -user.name.returns('ann') -api.received(1).getUser(1) -api.didNotReceive().getUser(1) // throws SubstituteException - -// Array.prototype.map calls getUser, so these calls are kept -const users = [1, 2].map(api.getUser) -users[1].name.returns('bob') -console.log(users[1].name) // prints bob -api.received(3).getUser(Arg.all()) - -// in the test, Reflect.apply() is part of the setup -const app = Substitute.for() -Reflect.apply(app.getUser, app, [2]).name.returns('bob') -console.log(app.getUser(2).name) // prints bob -app.received(1).getUser(2) -``` - -```js -const { Substitute, received } = require('@fluffy-spoon/substitute') - -// the code under test calls getUser from a promise job -const loadUser = (getUser, id) => Promise.resolve(id).then(getUser) - -async function test() { - const getUser = Substitute.for() - const user = await loadUser(getUser, 1) - user.name.returns('ann') - - console.log(user.name) // prints ann - getUser[received](1)(1) -} -test() -``` - -```js -const { Substitute, Arg } = require('@fluffy-spoon/substitute') - -// the code under test -const total = app => app.getCalculator().add(1, 2) - -const app = Substitute.for() -const calculator = Substitute.for() -app.getCalculator().returns(calculator) -// getCalculator() answers with a substitute, so this is one setup -app.getCalculator().add(1, 2).returns(3) - -console.log(total(app)) // prints 3 -app.received(1).getCalculator() -calculator.received(1).add(1, 2) - -// a fluent method that returns the substitute itself -const map = Substitute.for() -map.set(Arg.all()).returns(map) -console.log(map.set('b', 2) === map) // prints true -map.received(1).set('b', 2) -``` - -A check that a helper opens and its caller completes: - -```js -const { Substitute, Arg } = require('@fluffy-spoon/substitute') - -// test utilities: helpers that open a check for their caller to complete -const sentTo = (io, room) => io.to(room).received(1) -const userCheck = (api, id) => api.getUser(id).received(1) - -const io = Substitute.for() -io.to(Arg.any()).emit(Arg.all()).returns(true) -const api = Substitute.for() -// the code under test -io.to('room-a').emit('message', 'hi') -api.getUser(1).save() - -sentTo(io, 'room-a').emit('message', Arg.any()) -sentTo(io, 'room-b').emit('message', Arg.any()) // throws SubstituteException: but received none -userCheck(api, 1).save() -// the helpers' calls of to() and getUser() are part of the checks, so they are not recorded -io.didNotReceive().to('room-b') -io.received(1).to(Arg.any()) -api.received(1).getUser(1) -``` - -To read the stack frames, the library replaces `Error.prepareStackTrace` for a moment and then restores the exact property it found, so formatters such as `source-map-support` and `stack-chain` stay installed, and `Error.stack` stays a string. If the property cannot be replaced, the library reads no frames, and position alone decides, as above, although failure messages still have their `called at` lines. That is the case for: - -* a non-configurable, non-writable value. `Object.freeze(Error)` makes one on Node.js 20.20 and newer, where `Error` has an own `prepareStackTrace` (Node.js' own formatter); -* a missing property that cannot be added. On Node.js before 20.20, `Error` has no own `prepareStackTrace` unless a formatter installed one, so there `Object.freeze(Error)`, `Object.seal(Error)` and `Object.preventExtensions(Error)` all keep the library from reading frames. (On Node.js 20.20 and newer, a sealed or non-extensible `Error` keeps its writable `prepareStackTrace`, so the library reads frames.); -* a non-configurable accessor, which `stack-chain` defines when `Error.prepareStackTrace` is not already an own configurable property of `Error` when `stack-chain` loads (for example on Node.js 18; on Node.js 20.20, 22, 24 and 26 it is one, so the library reads frames there). - -The library leaves `Error.stackTraceLimit` alone: each operation captures as many frames as the limit says. When V8 collects no stack frames for any error, the library captures none either: with a limit that is an accessor (with or without a setter), that is missing (deleted), that is not a number (for example a string), or that is below 1, as with `Error.stackTraceLimit = 0`. Failure messages then have no `called at` lines, and position alone decides. - -```js -// for example in a hardened environment -Object.freeze(Error) -const { Substitute } = require('@fluffy-spoon/substitute') - -const calculator = Substitute.for() -calculator.add(1, 2).returns(3) -console.log(calculator.add(1, 2)) // prints 3 -calculator.received(2).add(1, 2) // throws SubstituteException -console.log(Error.stackTraceLimit) // prints 10 - -// the library cannot read frames, so position decides: the setup right after -// openConnection() leaves the call out (see the example at the top of this section) -function openConnection(driver) { - return driver.connect('db://test') -} -const driver = Substitute.for() -const connection = openConnection(driver) -connection.isOpen.returns(true) -driver.didNotReceive().connect('db://test') -driver.received(1).connect('db://test') // throws SubstituteException -``` - -# Verifying calls -## received and didNotReceive -`received()` checks that a call was received at least once, `received(count)` that it was received exactly `count` times, and `didNotReceive()` that it was never received. A failed check throws a [`SubstituteException`](#substituteexception). - - -```typescript -calculator.add(1, 2) -calculator.add(1, 2) -calculator.add(3, 4) - -calculator.received().add(1, 2) -calculator.received(2).add(1, 2) -calculator.received(3).add(Arg.all()) -calculator.didNotReceive().add(5, 6) -calculator.received(0).add(5, 6) // the same as didNotReceive() - -calculator.received(1).add(1, 2) // throws SubstituteException -``` - -The count must be a non-negative integer, or left out (meaning "1 or more"). Anything else (a negative or fractional number, `NaN`, `Infinity`, a string) throws a `SubstituteException` instead of letting the check pass: - - -```typescript -const items = ['a', 'b'] -calculator.received(items.length - 3).add(1, 2) // throws SubstituteException: Expected count has to be a non-negative integer -``` - -A check needs a call or a member after it. A check that nothing follows, such as `next.didNotReceive()` or `sub[received](2)` as a statement, checks nothing, so it is reported as a `SubstituteException`. The library cannot know right away whether something will follow, so the report comes later, from a microtask, like the [assertions that fail later](#assertions-that-fail-later), and its stack points at the line of the check, which every check records when it is made, in each of its forms. The message says how to complete it: `@Substitute.received(2) checked nothing: it was not followed by a call or a member. Complete the check: sub.received(2)(Arg.all()) checks the calls of the substitute itself, sub.received(2).member(...) the calls of one of its members, and sub.received(2).member its property reads.` For the string forms, a hint for types with a member called `received` or `didNotReceive` of their own follows. A nested substitute is named by its path (`@Substitute.logger.received()`), and so is a check [through a call with matchers](#through-a-call-with-matchers) (`@Substitute.on('saved', Arg.any{any})[received](1) checked nothing: ...`), and `received(0)` is reported as `didNotReceive()`. - -A check is complete when it is used before that microtask runs: by a member access, an assignment, a call or `new`. So a helper that returns `sub.received(1)` for its caller to complete is fine, and so is one that returns a check of a nested member or of a call's result, such as `app => app.logger.received(1)` or `(io, room) => io.to(room).received(1)`: the reads and calls that lead to the check belong to it, also when the caller completes it (see [Which calls lead to a setup or a check](#which-calls-lead-to-a-setup-or-a-check)). A helper whose check nothing follows is reported once for each check that it opened. Printing a check (`String()`, `util.inspect()`), `await`ing it, `key in check` and `Object.keys(check)` do not complete it, and neither does a member access after an `await`. (On Node.js 10, `util.inspect()` reads the `constructor` of a check, which makes it a property check of a member called `constructor`, so it throws a `SubstituteException` there.) `Object.freeze()`, `Object.seal()`, `Object.preventExtensions()` and `Object.defineProperty()` on a symbol-form check (`sub[received]()`, `sub[didNotReceive]()`) or on the [`configure`](#re-configuring-a-call-configure) view throw a `SubstituteException` that names the operation, and that check is not reported later. On the string forms (`sub.received(1)`, `sub.didNotReceive()`), which may be a call of a member of your own, they act on the auto-substitute of that call and succeed (it is frozen, or the property is defined on it), and the check is reported later as one that checks nothing. The string forms `sub.received(...)` and `sub.didNotReceive(...)` can also be a member of the substituted type that is called, so some of them are not reported; see [In JavaScript](#in-javascript). - -Each check that nothing follows is reported, also when the same check is made again, and completed, before the microtask runs: after `calculator.didNotReceive()` as a statement, a later `calculator.didNotReceive().add(3, 4)` does not hide it, and the report points at the line of the first. A string-form check hands out the same auto-substitute each time it is made with the same arguments (see [Auto-substitutes](#auto-substitutes-and-nested-members)), so each use of that auto-substitute completes one of the open checks that handed it out: the one made last. A check that is used is therefore never reported. One case slips through: a string-form check stored in a variable and used twice (`const check = sub.received(1); check.a(); check.b()`) uses up the report of an earlier `sub.received(1)` that nothing follows, which is then not reported. The symbol forms are tracked exactly, one report for each check. - -When a matcher in the arguments of a call of the check itself throws its `TypeError` for invalid use, as in `listener.received(1)(Arg.any('String'))`, `listener.didNotReceive()(Arg.is('x'))` or `sub.member.received(1)(Arg.is('bad'))`, that `TypeError` is the only error: no report that the check checked nothing follows. The rule is the one for property-style checks in [Assertions that fail later](#assertions-that-fail-later): the matcher is called on the same line as the check, after it, in the same function. - - -```typescript -calculator.add(1, 2) - -// a helper that returns a check for its caller to complete -const receivedOnce = () => calculator.received(1) -receivedOnce().add(1, 2) - -// nothing follows: reported later, from a microtask -calculator.didNotReceive() -// a complete check of the same form does not hide that report -calculator.didNotReceive().add(3, 4) -``` - -```js -const { Substitute, Arg, received } = require('@fluffy-spoon/substitute') - -const listener = Substitute.for() -listener('saved') -// the matcher throws for invalid use; the check is not reported later as one that checks nothing -listener.received(1)(Arg.any('String')) // throws TypeError -listener[received](1)(Arg.any('Strin')) // throws TypeError -listener.received(1)('saved') -``` - -A failed check describes what was expected and lists the calls that were received: at most 50 of them, and no more once the listed calls take 20,000 characters. A list that leaves some calls out ends with `› … and N more`. Each argument is printed within bounds (see [Printing a substitute](#printing-a-substitute)). For example: - - -```typescript -calculator.add(1, 2) -calculator.received().add(3, 4) // throws SubstituteException -``` - - -```text -SubstituteException: Call count mismatch in @Substitute.add: -Expected to receive 1 or more method calls matching add(3, 4), but received none. -All property or method calls to @Substitute.add received so far: -› ✘ @Substitute.add(1, 2) - called at Object. (test/calculator.test.ts:2:12) -``` - -The `called at` lines are stack frames, formatted by Node.js like any stack trace. Each recorded read or call captures its stack, and Node.js formats the text only when a message shows it. So source maps apply: with `node --enable-source-maps`, jest with `ts-jest`, vitest (also in its `vm` pools) and `tsx`, they name the lines of your TypeScript source. A formatter installed as `Error.prepareStackTrace` formats them, too: the one in place when the message is made. A `called at` line is the first line of that text that starts with `at`, also when the formatter writes no `Error` line above the frames; a formatter whose frames do not start with `at` gives no `called at` lines. A call through a method reference is shown where it was invoked; see [Which calls lead to a setup or a check](#which-calls-lead-to-a-setup-or-a-check). - -When the member was never used at all, the check fails as soon as it reads the member, before the arguments are known, so the message cannot name them: `Expected to receive 1 or more property reads or method calls matching add, but received none.` Once the method has been called, the message names the expected arguments, as above. - -A method that was read but never called fails a method check right away, whatever the count, with the reads listed and a hint: - - -```typescript -// the code under test registers a handler, which never fires -const handler = calculator.subtract -calculator.received(2).subtract(5, 1) // throws SubstituteException -``` - - -```text -SubstituteException: Call count mismatch in @Substitute.subtract: -Expected to receive 2 property reads or method calls matching subtract, but received 1 property read and no method calls. -All property or method calls to @Substitute.subtract received so far: -› ✘ @Substitute.subtract - called at Object. (test/calculator.test.ts:2:28) -@Substitute.subtract was read 1 time without being called; reading a method does not count as calling it. -``` - -So does a check that expects fewer calls than there were reads, as for code under test that looks at a callback before it uses it. For `didNotReceive()` and `received(0)`, the reads are what fails the check, so they are marked `✔`, and the hint ends with how to reset them (see the known issue in [What counts as a call](#what-counts-as-a-call)). - -```js -const { Substitute } = require('@fluffy-spoon/substitute') - -// the code under test reads the callback twice, and never calls it -const finish = options => { - if (typeof options.onDone === 'function') { - const done = options.onDone - } -} - -const options = Substitute.for() -finish(options) -options.received(1).onDone('ok') // throws SubstituteException: Expected to receive 1 property read or method call matching onDone, but received 2 property reads and no method calls. -``` - -A member whose reads answer values that cannot be called is checked as a property instead, and never gets that hint, since it is no method. A check without a call (`config.received(1).port`), and a check with a call whose count differs from the number of reads (`config.received(1).port()` after two reads, or `config.didNotReceive().port()`), fail as property checks: the message says "property reads", as in "Expected to receive 1 property read matching port, but received 2.", and marks the reads that it counts `✔`. A check with a call whose count equals the number of reads (`config.received(2).port()`, also `config[received](2).port()`), or with a call and no count (`config.received().port()`), passes as a property check and so fails as a method check: "Expected to receive 2 method calls matching port(), but received none.", with the reads marked `✘`, and a last line that says that the reads answered a value that cannot be called, and gives the check without the call (`sub.received(2).port`; it always shows the string form). A check with a call of a member that was not read at all says "property read or method call", as above. That is a member whose setups give such values: `returns()` of a value that is neither a function nor a substitute (also `returns()` without a value), `resolves()`, `rejects()` and `throws()`, and a member of a mimicked instance whose value is not a function, or that the instance does not have. The library decides this from the member's setups when the check is made. Members that may be methods keep the wording above: members that are not configured (their auto-substitutes can be called), members configured with a function, a substitute or `mimicks()`, members also configured as a method, and the methods and getters of a mimicked instance (the check does not run a getter to find out what it returns). - -```js -const { Substitute } = require('@fluffy-spoon/substitute') - -// the code under test reads the port twice -const connectionString = config => `postgres://localhost:${config.port}/app?port=${config.port}` - -const config = Substitute.for() -config.port.returns(5432) -connectionString(config) -config.received(1).port // throws SubstituteException -``` - - -```text -SubstituteException: Call count mismatch in @Substitute.port: -Expected to receive 1 property read matching port, but received 2. -All property or method calls to @Substitute.port received so far: -› ✔ @Substitute.port - called at connectionString (test/config.test.js:4:68) -› ✔ @Substitute.port - called at connectionString (test/config.test.js:4:94) -``` - -A check that calls it with the number of reads: - -```js -const { Substitute } = require('@fluffy-spoon/substitute') - -const connectionString = config => `postgres://localhost:${config.port}/app?port=${config.port}` - -const config = Substitute.for() -config.port.returns(5432) -connectionString(config) -config.received(2).port -config.received(2).port() // throws SubstituteException -``` - - -```text -SubstituteException: Call count mismatch in @Substitute.port: -Expected to receive 2 method calls matching port(), but received none. -All property or method calls to @Substitute.port received so far: -› ✘ @Substitute.port - called at connectionString (test/config.test.js:3:68) -› ✘ @Substitute.port - called at connectionString (test/config.test.js:3:94) -@Substitute.port was read 2 times, and its reads answered a value that cannot be called, so they are property reads, not method calls. To check them, leave out the call: sub.received(2).port -``` - -Every substitute prints as `@Substitute`, so when the code under test passes another substitute than the one a check expects, the expected call and the received one can print alike. Then the message numbers the substitutes in the order in which they appear in it, an auto-substitute with the number of the substitute it belongs to (`@Substitute#3.handler`), and its last line says so. The numbers hold only within that message, and only messages whose expected call (or assignment) prints like a listed call that it does not match, and that show more than one substitute, have them. Other messages, printouts and snapshots show `@Substitute`. Whether two lines print alike is decided as for printing them deeper (see below): a matcher in the expected call stands for the value that the listed call was given, and orders that matching ignores, such as the order of keys, do not count. So a check with a matcher for a generated id is numbered, too (the second example below), and so is one whose object the code under test builds as `{ ...input, id }`. A listed call that differs only where the expected call has a matcher that it does not match is not numbered when the substitutes are the same. The substitutes of another copy of the package are numbered along with the others, when both copies are this version or newer (see [The symbol API](#the-symbol-api)). - -```js -const { Substitute } = require('@fluffy-spoon/substitute') - -// the code under test mounts the wrong handler -const mount = (app, handlers) => app.use('/admin', handlers.public) - -const app = Substitute.for() -const adminHandler = Substitute.for() -const publicHandler = Substitute.for() -mount(app, { admin: adminHandler, public: publicHandler }) -app.received(1).use('/admin', adminHandler) // throws SubstituteException -``` - - -```text -SubstituteException: Call count mismatch in @Substitute#1.use: -Expected to receive 1 method call matching use('/admin', @Substitute#2), but received none. -All property or method calls to @Substitute#1.use received so far: -› ✘ @Substitute#1.use('/admin', @Substitute#3) - called at mount (test/app.test.js:4:41) -The substitutes are numbered in this message (@Substitute#1, @Substitute#2, ...) to tell them apart. -``` - -```js -const { Substitute, Arg } = require('@fluffy-spoon/substitute') - -const bus = Substitute.for() -const app = Substitute.for() -const plugin = Substitute.for() -// the code under test subscribes the plugin's handler, with an id that it generates -bus.subscribe({ id: 'sub-81f3', handler: plugin.onEvent }) - -bus.received(1).subscribe({ id: Arg.any('string'), handler: app.onEvent }) // throws SubstituteException: matching subscribe({ id: Arg.any{string}, handler: @Substitute#2.onEvent }), but received none. -``` - - -```text -SubstituteException: Call count mismatch in @Substitute#1.subscribe: -Expected to receive 1 method call matching subscribe({ id: Arg.any{string}, handler: @Substitute#2.onEvent }), but received none. -All property or method calls to @Substitute#1.subscribe received so far: -› ✘ @Substitute#1.subscribe({ id: 'sub-81f3', handler: @Substitute#3.onEvent }) - called at Object. (test/bus.test.js:7:5) -The substitutes are numbered in this message (@Substitute#1, @Substitute#2, ...) to tell them apart. -``` - -Arguments are printed two levels deep (see [Printing a substitute](#printing-a-substitute)), and so is the value of an assignment. When the expected call and a received one that it does not match would still print alike, because they differ further down, as filters of an ORM often do, the message prints the expected line and those received lines deeper: at the least depth, up to four levels, at which they print differently. A matcher in the expected call does not count as a difference here: it prints by its label, such as `Arg.any{string}`, where the received call shows the value that it was given. So a check with a matcher for a generated id, a timestamp or a callback is printed deeper, too, when the calls differ further down somewhere else (the second example below), also inside a `Map` or a `Set`: `save(Arg.any{string}, { order: { meta: { tags: Set(1) { 'express' } } } })` against `@Substitute.save('ord-1', { order: { meta: { tags: Set(1) { 'gift' } } } })`. Neither does an order that matching ignores: the order of keys, as in an object that the code under test builds as `{ ...input, id }` (the third example below), the order of the entries of a `Map` or a `Set` built in another order, such as a `Set` of tags or a `Map` of headers made from `Object.entries()` (the fourth example below), the order of the own properties of an error or a function, and such orders inside them, such as the keys of an object held by an error's property or `cause`, or of the objects in a `Set`. Such lines are printed as deep as a difference further down needs, each with its keys and entries in its own order. Received lines that print differently two levels deep in another way stay two levels deep, and so do lines that differ only where the expected call has a matcher that they do not match: for an expected `f(Arg.is{n => n > 5}, { a: { b: { c: [Object] } } })`, a received `f(3, { a: { b: { c: [Object] } } })` with the same object. A matcher inside a `Map`, a `Set` or a class instance is a value, as when matching (see [Matchers inside objects and arrays](#matchers-inside-objects-and-arrays)), so it is a difference there: `f(Arg.any{any}, Map(1) { 'k' => Arg.any{any} })` against `@Substitute.f('x', Map(1) { 'k' => 1 })` stays two levels deep. Calls that differ only deeper than four levels print alike, two levels deep. To find the depth, the message prints the expected call, with each matcher in it replaced by the value that the received call has at its place (at the top level and inside plain objects and arrays), and the received call, at each depth from two levels (or as deep as the object that holds the deepest matcher) up to four, in two ways: as the message prints them, and with the keys of objects, the entries of `Map`s and `Set`s and the properties of errors and functions in a fixed order, without the cut after 1,000 characters. A line is printed at the least depth at which the two calls differ in both texts. So what counts is what the lines show: the keys of objects, in any order; the items of arrays, and their other keys, such as the `total` of an array of rows or the `index` and `input` of a `RegExp` match; the size, the first 20 entries, in any order, and the other keys of `Map`s and `Set`s; the part of a long string that is shown; errors and functions with properties, with their properties and everything inside them in any order; and other values, such as typed arrays, `Date`s and objects that print themselves, by their printed text. A difference in the part of a value that is cut off after 1,000 characters counts only when it changes the number of characters left out, and an order does not count there either. On Node.js 10.0 to 10.11, whose `util.inspect()` cannot sort, an order inside the properties of errors and functions, or inside the members of a `Set`, still counts as a difference. Every listed line is compared in this way. Matchers in the expected call are shown by their own label at any depth, with the objects and arrays that hold them, and when a matcher is deeper than two levels, the received calls that it does not match are printed as deep as the object that holds it (at most four levels), so they show the value that the matcher was given: for an expected `{ a: { b: { c: { d: Arg.is{value => value > 5} } } } }`, a received call shows `{ a: { b: { c: { d: 1, e: [Object] } } } }`. The numbering of substitutes goes by the lines as printed, so two calls that differ only in which substitute sits inside a cut-off object (`use({ a: { b: { c: [Object] } } })`) print alike and are not numbered. `util.inspect()` puts at most 80 characters and three levels of nested objects on one line, so the lines printed deeper span several lines, as below. - -```js -const { Substitute } = require('@fluffy-spoon/substitute') - -const prisma = Substitute.for() -// the code under test -prisma.user.findMany({ where: { AND: [{ email: { contains: 'ann' } }] } }) - -prisma.user.received(1).findMany({ where: { AND: [{ email: { contains: 'bob' } }] } }) // throws SubstituteException -``` - - -```text -SubstituteException: Call count mismatch in @Substitute.user.findMany: -Expected to receive 1 method call matching findMany({ - where: { - AND: [ { email: { contains: 'bob' } } ] - } -}), but received none. -All property or method calls to @Substitute.user.findMany received so far: -› ✘ @Substitute.user.findMany({ - where: { - AND: [ { email: { contains: 'ann' } } ] - } -}) - called at Object. (test/users.test.js:5:13) -``` - -With a matcher for an id that the code under test generates, the lines differ only further down elsewhere, so they are printed deeper as well: - -```js -const { Substitute, Arg } = require('@fluffy-spoon/substitute') - -const users = Substitute.for() -// the code under test saves a user with a generated id -users.save({ id: 'u-81f3', profile: { address: { geo: { lat: 59.9, lng: 10.7 } } } }) - -users.received(1).save({ id: Arg.any('string'), profile: { address: { geo: { lat: 60.4, lng: 5.3 } } } }) // throws SubstituteException -``` - - -```text -SubstituteException: Call count mismatch in @Substitute.save: -Expected to receive 1 method call matching save({ - id: Arg.any{string}, - profile: { address: { geo: { lat: 60.4, lng: 5.3 } } } -}), but received none. -All property or method calls to @Substitute.save received so far: -› ✘ @Substitute.save({ - id: 'u-81f3', - profile: { address: { geo: { lat: 59.9, lng: 10.7 } } } -}) - called at Object. (test/users.test.js:5:7) -``` - -With an object that the code under test builds from its input, whose keys come in another order: - -```js -const { Substitute, Arg } = require('@fluffy-spoon/substitute') - -const users = Substitute.for() -// the code under test adds a generated id to its input -const input = { name: 'Ann', address: { geo: { point: { lat: 59.9, lng: 10.7 } } } } -users.save({ ...input, id: 'u-81f3' }) - -users.received(1).save({ id: Arg.any('string'), name: 'Ann', address: { geo: { point: { lat: 60.4, lng: 5.3 } } } }) // throws SubstituteException -``` - - -```text -SubstituteException: Call count mismatch in @Substitute.save: -Expected to receive 1 method call matching save({ - id: Arg.any{string}, - name: 'Ann', - address: { geo: { point: { lat: 60.4, lng: 5.3 } } } -}), but received none. -All property or method calls to @Substitute.save received so far: -› ✘ @Substitute.save({ - name: 'Ann', - address: { geo: { point: { lat: 59.9, lng: 10.7 } } }, - id: 'u-81f3' -}) - called at Object. (test/users.test.js:6:7) -``` - -With a `Set` whose entries come in another order: - -```js -const { Substitute } = require('@fluffy-spoon/substitute') - -const posts = Substitute.for() -// the code under test collects the tags in the order in which it finds them -posts.publish({ id: 'p1', tags: new Set(['news', 'tech']), author: { profile: { address: { city: 'Oslo' } } } }) - -posts.received(1).publish({ id: 'p1', tags: new Set(['tech', 'news']), author: { profile: { address: { city: 'Bergen' } } } }) // throws SubstituteException -``` - - -```text -SubstituteException: Call count mismatch in @Substitute.publish: -Expected to receive 1 method call matching publish({ - id: 'p1', - tags: Set(2) { 'tech', 'news' }, - author: { profile: { address: { city: 'Bergen' } } } -}), but received none. -All property or method calls to @Substitute.publish received so far: -› ✘ @Substitute.publish({ - id: 'p1', - tags: Set(2) { 'news', 'tech' }, - author: { profile: { address: { city: 'Oslo' } } } -}) - called at Object. (test/posts.test.js:5:7) -``` - -When an expected line still prints exactly like a received line that it does not match, also after printing them deeper, the message ends with a note that says why they can differ, once per message (after the note on numbered substitutes, if there is one): `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.` That happens with objects that hold functions, such as the commands of the AWS SDK with their middleware, with classes that keep their state in `#private` fields (see [How arguments are compared](#how-arguments-are-compared)), and with symbols of the same description. When the lines show that the message leaves something out, such as `[Object]`, `[Getter]`, `... 1 more key` or `… (40 more characters)`, the note says that they can differ there, too: `Some calls print the same but do not match: they can differ in what the message leaves out ([Object], more keys, items or characters), functions and symbols ...`. For a check of an assignment, it starts with `Some assignments print the same but do not match:` and ends with `Match such values with Arg.is(), or assign the same instance.` The note compares the lines as the message prints them, without colours; lines that print differently, also only in the numbers of their substitutes, get no note. - -```js -const { Substitute, Arg } = require('@fluffy-spoon/substitute') - -// a command with a middleware stack of functions, as the AWS SDK makes them -class GetItemCommand { - constructor(input) { - this.input = input - this.middleware = { use: () => { } } - } -} - -const client = Substitute.for() -// the code under test -client.send(new GetItemCommand({ TableName: 'inventory' })) - -client.received(1).send(new GetItemCommand({ TableName: 'inventory' })) // throws SubstituteException -// check what matters with a matcher instead -client.received(1).send(Arg.is(command => command instanceof GetItemCommand && command.input.TableName === 'inventory')) -``` - - -```text -SubstituteException: Call count mismatch in @Substitute.send: -Expected to receive 1 method call matching send(GetItemCommand { - input: { TableName: 'inventory' }, - middleware: { use: [Function: use] } -}), but received none. -All property or method calls to @Substitute.send received so far: -› ✘ @Substitute.send(GetItemCommand { - input: { TableName: 'inventory' }, - middleware: { use: [Function: use] } -}) - called at Object. (test/client.test.js:13:8) -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. -``` - -The message contains ANSI colours only when the output is a terminal. `NO_COLOR`, `NODE_DISABLE_COLORS` and `TERM=dumb` turn colours off, and `FORCE_COLOR` turns them on. - -## Properties -`received().property` counts reads of a property, and `received().property = value` counts assignments of that value (matchers work here as well). - - -```typescript -// the code under test reads the property and sets it -const toggle = (c: Calculator) => { c.isEnabled = !c.isEnabled } - -calculator.isEnabled.returns(false) -toggle(calculator) - -calculator.received(1).isEnabled -calculator.received().isEnabled = true -calculator.received(1).isEnabled = Arg.any() -calculator.didNotReceive().isEnabled = false -``` - -Assigning a property is recorded, but it does not change what the property reads, unlike NSubstitute's auto-properties: after `settings.mode = 'HEX'`, `settings.mode` is still an auto-substitute, and after `settings.mode.returns('DEC')` and `settings.mode = 'BIN'`, it is still `'DEC'`. Configure the value with `returns()`, or mimick a plain object (`client[mimick]({ baseUrl: '' })`, which compiles in TypeScript, too, as a partial instance; see [Partial mocks](#partial-mocks)): assignments then write to that object, and reads give the value back. Both are still recorded. - -```js -const { Substitute, mimick } = require('@fluffy-spoon/substitute') - -const settings = Substitute.for() -settings.mode.returns('DEC') -settings.mode = 'BIN' // the code under test assigns the property -console.log(settings.mode) // prints DEC -settings.received(1).mode = 'BIN' - -const client = Substitute.for() -client[mimick]({ baseUrl: '' }) -client.baseUrl = 'https://api' -console.log(client.baseUrl) // prints https://api -client.received(1).baseUrl = 'https://api' -client.received(1).baseUrl -``` - -In TypeScript, assigning a property on the substitute itself (`calculator.isEnabled = true`) does not compile, see [Typing limitations](#typing-limitations). The code under test assigns through its own type, like `toggle` above. In a check, read-only properties can be assigned, and optional properties that are not functions accept `undefined` (`form.received().note = undefined`). An optional callback (`onChange?: (value: string) => void`) does not; see [Typing limitations](#typing-limitations) for how to check that it was cleared. - -## What counts as a call -* Every invocation is a call of its own, also through a stored or destructured reference or a callback. -* `new` is a call, too: `new sdk.Client('https://api')` counts as a call `Client('https://api')` (see [Creating a substitute](#creating-a-substitute)). -* A call that leaves out arguments at the end is a call with `undefined` there: `f(1)` and `f(1, undefined)` count as the same call (see [How arguments are compared](#how-arguments-are-compared)). -* `.call()`, `.apply()` and `.bind()` work on a method, a function substitute and every other substitute value as on a function: `calculator.subtract.call(undefined, 5, 1)` answers what `calculator.subtract(5, 1)` answers, the configured value or, when nothing is configured, the same auto-substitute, and counts as a call `subtract(5, 1)`. (That is so when the first argument is `undefined`, `null`, an object or a function; with a string or another primitive, as in an RPC client's `rpc.call('getUser', 1)`, a call that is not configured gets an auto-substitute of its own: see [`call`, `apply` and `bind`](#call-apply-and-bind).) So a wrapper that forwards a call with `fn.apply(this, args)`, as retry, `once`, memoize and debounce helpers, middleware, `jest.fn(fn)`, `vi.fn(fn)` and `sinon.spy(fn)` do, gets what the direct call gets: the setups made on `api.getUser(1)` answer through `withRetry(api.getUser)(1)`, and the calls made on what it returned are checked on `api.getUser(1)` (the second example below). It counts as a call of a member called `call` as well; see [`call`, `apply` and `bind`](#call-apply-and-bind). -* Reading a method without calling it, for example to register it as an event handler that never fires, is not a call. Method checks (`received().subtract(...)`, also with `Arg.all()`) only count invocations. -* A call with an argument matcher (`Arg.any()`, `Arg.is()`, `Arg.all()`, also with `.not`, also [inside an object or array](#matchers-inside-objects-and-arrays), and the [matchers of test runners](#matchers-of-test-runners), such as `expect.any(String)`) is a setup or a check, never a received call. It does not run an existing setup either. A check through such a call, like `repo.find(Arg.any()).received(1).save()`, checks the substitutes that the received calls it matches returned (see [Through a call with matchers](#through-a-call-with-matchers)). -* The reads and calls that lead up to a setup or a check in the same expression are not recorded; see [Which calls lead to a setup or a check](#which-calls-lead-to-a-setup-or-a-check). -* What a matcher does while it looks at an argument is not a call either: the reads, calls and assignments that an `Arg.is()` predicate, or a matcher of a test runner, makes on a substitute argument are not recorded, in checks and in calls of the code under test that are compared with setups. In a check, nothing that it does while it runs is recorded (what an `async` callback that it calls does after its first `await` is); when a call is compared with setups, what a callback that it calls does, and what it does to substitutes that are not among the arguments, is recorded (see [Matching specific arguments](#matching-specific-arguments)). -* Checks never run setups or mimicked implementations, and are never recorded themselves. Checking a property configured with `throws()` does not throw, and checking a property configured with a sequence does not use up a value, nor does a predicate of a check that reads it. - - -```typescript -const { add } = calculator -for (const n of [1, 2, 3]) add(n, n) -calculator.received(3).add(Arg.all()) - -const handler = calculator.subtract -calculator.received().subtract(Arg.all()) // throws SubstituteException - -calculator.subtract(5, 1).returns(4) -console.log(calculator.subtract.call(undefined, 5, 1)) // prints 4 -calculator.received(1).subtract(5, 1) - -calculator.divide(Arg.any(), 2) // a setup without a value, not a call -calculator.didNotReceive().divide(Arg.all()) -``` - -```js -const { Substitute } = require('@fluffy-spoon/substitute') - -// the code under test loads a user through a wrapper that forwards with apply(), and saves it -const withRetry = fn => function (...args) { return fn.apply(this, args) } -const touch = (api, id) => { - const user = withRetry(api.getUser)(id) - user.save() - return user.name -} - -const api = Substitute.for() -api.getUser(1).name.returns('bob') - -console.log(touch(api, 1)) // prints bob -api.received(1).getUser(1) -api.getUser(1).received(1).save() -``` - -**Known issue in 2.0.1:** `didNotReceive().subtract(...)` (or `received(0)`) on a method that has been read but never called fails, because the library decides at `.subtract` whether you check a property read or a method call. The message says so: `Expected to receive 0 property reads or method calls matching subtract, but received 1 property read and no method calls.`, followed by a hint that ends with `Call sub[clearReceivedCalls]() after the arrange step to reset the reads.` If the code under test registers a method without calling it, clear the received calls after that (see below) before you check that it was not called. - - -```typescript -import { clearReceivedCalls } from '@fluffy-spoon/substitute' - -// the code under test registers a handler, which never fires -const register = (c: Calculator) => c.subtract -register(calculator) - -calculator.didNotReceive().subtract(Arg.all()) // throws SubstituteException: Expected to receive 0 property reads or method calls matching subtract, but received 1 property read and no method calls. -calculator[clearReceivedCalls]() -calculator.didNotReceive().subtract(Arg.all()) -``` - -## Clearing received calls -`sub[clearReceivedCalls]()` forgets the received calls of a substitute and of its auto-substitutes. Setups are kept, including the position in a sequence of return values, and so are the auto-substitutes (`app.logger` stays the same object). To start over completely, create a new substitute. A substitute of your own that a setup returns (`io.to(Arg.any()).returns(room)`) keeps its calls, as it is cleared only by its own `[clearReceivedCalls]()`, but a check through `sub` no longer counts the calls that it received through what `sub` handed out before the clear (see [Through a call with matchers](#through-a-call-with-matchers)). - - -```typescript -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 3 -``` - -## SubstituteException -Failed checks, and invalid use of the library such as `received(-1)` or arguments after `Arg.all()`, throw a `SubstituteException`. It is exported, so you can check for it with `instanceof`: - - -```typescript -import { SubstituteException } from '@fluffy-spoon/substitute' - -try { - calculator.received().add(1, 2) -} catch (error) { - console.log(error instanceof SubstituteException) // prints true -} -``` - -## Assertions that fail later -Checks throw right away, with two exceptions. One is a check that nothing follows, like `sub.didNotReceive()` as a statement, which checks nothing (see [received and didNotReceive](#received-and-didnotreceive)). The other is a property-style check, `sub.received(count).member` or `sub.didNotReceive().member` that is not followed by a call, on a member that has been called as a method. The library cannot know yet whether you are about to call it (`sub.received(2).member(...)`), so it reports the failure later, from a microtask (`queueMicrotask`; `process.nextTick` on Node.js 10, which has no `queueMicrotask`), and cancels the report if you call the member. There are two cases: - -* The property check fails, as in `calculator.received(2).add` below. -* `didNotReceive().member` or `received(0).member` on a member that was only called, never read: it would pass as a property check, but the parentheses were probably forgotten. The report says so: `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(...)`. - -Such a failure escapes `try`/`catch` and `t.throws()`: it is an uncaught exception, thrown from a microtask once the current synchronous code has finished. Its stack has one frame, the line of the check. (So does the report of a check that nothing follows; see [received and didNotReceive](#received-and-didnotreceive).) That frame is the first line of the check's stack that starts with `at`, as for [`called at` lines](#received-and-didnotreceive): with an `Error.prepareStackTrace` that writes more lines for each frame, such as the code of the line, the report keeps only that one, and with one whose frames do not start with `at`, it keeps the second line of the check's stack, which is the line of the check when the formatter writes an `Error` line first. Each report is thrown from a microtask of its own, which the check queues when it is made, so the reports come in the order of the checks, and a microtask that the test queues after the checks runs after their reports. - - -```typescript -calculator.add(1, 2) -calculator.add(1, 2) -calculator.add(3, 4) - -// not followed by a call, so the library cannot decide yet: -// the SubstituteException is thrown later, from a microtask -calculator.received(2).add -``` - - -```typescript -calculator.add(1, 2) - -// the parentheses are missing: reported later, from a microtask -calculator.didNotReceive().add -``` - -To avoid this, check methods with a call (`calculator.received(2).add(1, 2)`, or `.add(Arg.all())`). Those are decided right away. - -When a matcher in such a check throws its `TypeError` for invalid use, as `Arg.any('String')` and `Arg.is('x')` do, that `TypeError` is the only error: `calculator.received(2).add(Arg.any('String'), 1)` reports nothing later. The library takes a matcher for a part of the check when it is called on the same line as the member is read, after it, in the same function (the line of the source, also in transpiled test files that have a source map; see [Which calls lead to a setup or a check](#which-calls-lead-to-a-setup-or-a-check)). That includes a chain over several lines whose arguments start on the line of the member (`.add(Arg.any('String'), 1)`). A check whose arguments start on a later line than the member (`.add(` and then, on the next line, `Arg.any('String'), 1)`), or a run without stack traces (`Error.stackTraceLimit = 0`), reports both: the `TypeError` right away, and the check later. A matcher that throws anywhere else never cancels the report of an earlier check: in a later statement, or in another function (also on the same line, such as `expect(() => Arg.any('Strin')).toThrow()`). Only a statement after the check on the same line, in the same function, cannot be told apart from the check itself: `void s.didNotReceive().m; Arg.any('Strin')` on one line reports only the `TypeError`. The same rule decides for a check that is called itself, such as `listener.received(1)(Arg.any('String'))` (see [received and didNotReceive](#received-and-didnotreceive)), and there, too, a statement after the check on the same line counts as part of it: `s[received](1); try { Arg.any('x') } catch { }` on one line is not reported as a check that checks nothing. - - -```js -const { Substitute, Arg } = require('@fluffy-spoon/substitute') - -const sub = Substitute.for() -sub.m(1) -void sub.didNotReceive().m // reported later: m was called as a method -try { Arg.any('Strin') } catch { } // a usage error in another statement does not cancel that report -``` - -Every test runner fails the run, but not all of them can tie the failure to the test, and two of them stop running tests. Seen with jest 29.7 and 30.5, vitest 5.1, ava 6.4, mocha 11.8 and 12.0 and node:test on Node.js 22, 24 and 26; the [compatibility checks](#test-runners) pin this for jest 30, vitest, ava, mocha (with a synchronous and with an `async` test) and node:test on every change, with passing tests before and after the failing one (and, for mocha and ava, a second test file): - -* jest 29, and jest 30 on Node.js 24 and newer: as the failure of the running test (`● `). The other tests and test files still run and are reported, in band and with workers. -* jest 30 on Node.js 22: as a failure of the test file ("Test suite failed to run"). The other tests in the file still run and pass, and the run fails. (Node.js 22 loses the test context that jest 30 looks up for an exception thrown from a microtask.) -* vitest: every test runs and is listed as passed, and the run fails with one error: an "Unhandled Errors" entry with the `SubstituteException`, which names the test ("The last test to run before this error was ..."). This holds with `vi.useFakeTimers()` and in the `vm` pools, too. -* node:test: every test runs and passes, and the test file fails ("A resource generated asynchronous activity after the test ended", with the `SubstituteException`). -* mocha, in a synchronous test: the test is listed as passed (`✔ `) and then as failed (`1) `, with "Uncaught SubstituteException"), so the summary counts it both as passing and as failing. **Then mocha stops the run:** the tests after it in the same file, and every test in later files, do not run and are not listed. The run exits with a non-zero code. mocha marks a synchronous test as passed as soon as it returns, so no other way of reporting the failure later could change this. -* mocha, in an `async` test (or another test that returns a promise) whose check fails later while its promise is still pending, as after an `await`: as the failure of that test (`1) `, with "Uncaught SubstituteException: Call count mismatch ..."; mocha 11 writes "Uncaught Call count mismatch ..." and the `SubstituteException` below it), and then the same test a second time when its promise settles (`2) `, with "Error: done() called multiple times in test <...>"), so the summary counts two failures for it. The tests after it, also in later files, run and are reported, and the run exits with a non-zero code. That second report needs the run to still be going when the promise settles: if the test's promise settles only after the last test has finished, the summary counts one failure for it (`3 passing, 1 failing`), and then mocha throws "Error: done() called multiple times in test <...>" (`ERR_MOCHA_MULTIPLE_DONE`) as an uncaught exception after the summary, and the process exits with code 7. -* ava: `Uncaught exception in ` with the `SubstituteException`, the failing test listed as passed (`√ `), `× exited with a non-zero exit code: 1`, and "1 uncaught exception" in the summary. **ava ends the worker of that test file:** the tests of that file that had not finished are not reported at all. ava runs the tests of a file concurrently, so this includes `async` tests written before the failing one. Tests in other files, which run in other workers, are reported as usual. The run exits with a non-zero code. -* Plain Node.js prints the uncaught exception and exits with code 1. - -With mocha (in a synchronous test) and ava, a check that fails later can therefore hide the results of other tests, including other failures. Fix it first, or avoid it altogether by checking methods with a call, as above. - -The report is scheduled with the `queueMicrotask` that the library found when it was loaded, so fake timers that are installed later, such as `jest.useFakeTimers()` or `vi.useFakeTimers()` in a test, or `@sinonjs/fake-timers` faking `queueMicrotask` and `nextTick`, do not delay or swallow it. Fake timers that replace `queueMicrotask` before the library is loaded, for example jest's `fakeTimers: { enableGlobally: true }` configuration or a setup file that installs them before the library is imported, can delay the report until the fake clock runs its microtasks. - -# Names that conflict with the library -A substituted type may have members with the same names as the library's methods: `received`, `didNotReceive`, `returns`, `throws`, `resolves`, `rejects` or `mimicks`. Each of them has a symbol (exported from the package) that always means the library method. Members called `call`, `apply` or `bind` need care too, because every function has them; see [`call`, `apply` and `bind`](#call-apply-and-bind). - -## In TypeScript -If the substituted type has a member with one of these names, `sub.received()` and `sub.didNotReceive()` are not offered, because they would be ambiguous. Use the symbols `sub[received]()` and `sub[didNotReceive]()`; they are always available. - -In generic code, the type parameter's constraint decides. A type parameter without a constraint gets the string forms: `sub.received()` and `sub.didNotReceive()` are offered on `SubstituteOf`, and the setup methods on calls that return `T`. For `T extends Account`, where `Account` has a member called `returns`, only the symbols are offered, as for `Account` itself. -```typescript -import { Substitute, Arg, received } from '@fluffy-spoon/substitute' - -class Example { - received(someNumber: number) { - return someNumber - } -} - -const fake = Substitute.for() - -// `fake.received` is the class' own method -fake.received(1).returns(2) -console.log(fake.received(1)) // prints 2 - -// check it with the symbol -fake[received]().received(1) -fake[received](1).received(Arg.any()) -fake[received](2).received(1) // throws SubstituteException -``` - -In the same way, `.returns()`, `.throws()`, `.mimicks()`, `.resolves()` and `.rejects()` are not offered on a value that has its own member with that name. That value is the property's type, or the return type of the call. Use the symbols `[returns]`, `[throws]`, `[mimicks]`, `[resolves]` and `[rejects]` there; they always work. - -```typescript -import { Substitute, returns } from '@fluffy-spoon/substitute' - -interface Order { - returns: string[] - total(): number -} - -interface Shop { - find(id: string): Order -} - -const shop = Substitute.for() -const order = Substitute.for() - -// an Order has a member called `returns`, so shop.find('1').returns is that member -shop.find('1')[returns](order) -order.total().returns(42) - -console.log(shop.find('1').total()) // prints 42 -``` - -At runtime, `.returns`, `.throws`, `.resolves`, `.rejects` and `.mimicks` on a member or call that is *not* configured always mean the setup methods. So if the code under test uses a member with one of these names on a value it gets from a substitute, configure that value first, as `shop.find('1')` above. - - -```typescript -import { Substitute, SubstituteOf, CheckViewOf, Arg, didNotReceive } from '@fluffy-spoon/substitute' - -interface Repository { - get(id: string): T -} - -function stubGet(repository: SubstituteOf>, value: T) { - repository.get(Arg.any()).returns(value) -} - -// CheckViewOf is what received() and didNotReceive() return, in the string and the symbol forms -function receivedOnce(sub: SubstituteOf): CheckViewOf { - return sub.received(1) -} - -function neverReceived(sub: SubstituteOf): CheckViewOf { - return sub[didNotReceive]() -} -``` - - -```typescript -const users = Substitute.for>() -stubGet(users, 'ann') -console.log(users.get('1')) // prints ann -receivedOnce(users).get('1') -neverReceived(users).get('2') -``` - -With a constrained type parameter, such as in a helper or a test fixture written for every `T extends Calculator`, setups, checks and the `configure` view work through the constraint, also for keys that exist only through the constraint's string index signature, and the values they take are checked against the constraint's member types. [Typing limitations](#typing-limitations) lists the exceptions: optional and nullable members on TypeScript older than 4.8, methods whose return type differs between the variants of a union constraint (and, on TypeScript 5.4 and newer, methods that they declare with different parameter lists), checks of sets of keys that exist only through an index signature, and `.resolves()` on promise-typed properties. - -```typescript -import { Substitute, SubstituteOf, Arg, configure } from '@fluffy-spoon/substitute' - -interface Calculator { - add(a: number, b: number): number - total: number -} - -interface ScientificCalculator extends Calculator { - sqrt(x: number): number -} - -class CalculatorFixture { - readonly calculator: SubstituteOf = Substitute.for() - - arrange() { - this.calculator.add(Arg.all()).mimicks((a, b) => a + b) - this.calculator.total.returns(10) - this.calculator[configure]().add(0, 0).returns(-1) - } - - verifyAdded(a: number, b: number) { - this.calculator.received(1).add(a, b) - } -} - -const fixture = new CalculatorFixture() -fixture.arrange() -fixture.calculator.sqrt(4).returns(2) - -console.log(fixture.calculator.add(1, 2)) // prints 3 -console.log(fixture.calculator.add(0, 0)) // prints -1 -console.log(fixture.calculator.total + fixture.calculator.sqrt(4)) // prints 12 -fixture.verifyAdded(1, 2) -``` - -`clearReceivedCalls`, `mimick` and `configure` exist only as symbols, so members with those names never conflict. - -## In JavaScript -Without types, the library decides by how a name is used: - -* `sub.received(...)` and `sub.didNotReceive()` are checks when they are called and followed by a member, like `sub.received(2).add(1, 2)`. Followed by `.returns()`, `.throws()`, `.resolves()`, `.rejects()` or `.mimicks()`, they configure a member of your own called `received` or `didNotReceive`. -* Called and followed by nothing, as a statement like `next.didNotReceive()` or `res.received(2)`, they are reported as a check that checks nothing (see [received and didNotReceive](#received-and-didnotreceive)), unless the call is most likely one of a member of your own: when its arguments are not those of a check (`received` with more than one argument, or with anything but a non-negative integer, and `didNotReceive` with any argument, as in `mailbox.received(new Date(0))`), when a setup or a mimicked instance answers it (`sub.received(1).returns(2)` and then `sub.received(1)`), or when, by the time the report would be made, the member has a setup or a check has named it as a member (`sub[received](1).received(10)`). Such a call is recorded as a call of the member, as always. The report's message adds how to keep such calls from being taken for checks: configure them, as below. -* `sub.received` that is not called is an ordinary member, so the code under test can read a property called `received`. -* `sub.received(count)` or `sub.didNotReceive()` followed directly by a call checks a call of the substitute itself: `listener.received(1)('saved')` checks that the function substitute `listener` was called with `'saved'`. On a member, `sub.method.received(1)(5)` checks the calls `sub.method(5)`. -* The symbols `sub[received]()` and `sub[didNotReceive]()` are always checks. Use them to check members called `returns`, `throws`, `resolves`, `rejects` or `mimicks`. - -```js -const { Substitute, received } = require('@fluffy-spoon/substitute') - -const mailbox = Substitute.for() -mailbox.received(1).returns(['mail']) -console.log(mailbox.received(1)) // prints [ 'mail' ] - -const builder = Substitute.for() -builder.returns(5) // the code under test calls its own `returns` method -builder[received]().returns(5) -``` - -These rules are applied at runtime, so they apply to the code under test as well, in TypeScript as in JavaScript, whatever its types say. When the code under test calls a member called `received` (or `didNotReceive`) of a substitute and then uses a member of the result, the library takes it for a check, unless that call is configured: `mailbox.received(new Date(0)).filter(mail => !mail.read)` throws `SubstituteException: Expected count has to be a non-negative integer (or omitted for "1 or more"), but received 1970-01-01T00:00:00.000Z.` Configure every call that the code under test can make, for example `mailbox[configure]().received(Arg.any()).returns([])`, or mimick an instance (`mailbox[mimick](realMailbox)`), and check those calls with the symbol: `mailbox[received](1).received(Arg.any())`. A setup for other arguments only (`mailbox[configure]().received(new Date(1)).returns([])`) does not help a call with another date. - -```js -const { Substitute, Arg, configure, received } = require('@fluffy-spoon/substitute') - -// the code under test calls the mailbox's own `received(since)` method -const unread = (mailbox, since) => mailbox.received(since).filter(mail => !mail.read) - -const unconfigured = Substitute.for() -unread(unconfigured, new Date(0)) // throws SubstituteException: Expected count has to be a non-negative integer - -const mailbox = Substitute.for() -mailbox[configure]().received(Arg.any()).returns([{ read: false }, { read: true }]) -console.log(unread(mailbox, new Date(0)).length) // prints 1 -mailbox[received](1).received(Arg.any()) -``` - -## call, apply and bind -Every function has `call`, `apply` and `bind`, and a substituted object can have members with these names of its own, like the `call(method, ...args)` of an RPC client or the `bind(port)` of a socket. On every substitute value that can be called (a substitute, a member like `sub.method`, the result of a call, a nested auto-substitute), `x.call`, `x.apply` and `x.bind` therefore give a helper that handles both meanings: - -* If a setup for a member called `call`, `apply` or `bind` matches the arguments as they are, it answers. Such a setup comes from `x.call('getUser', 1).returns(user)`, from the `configure` view, or from a mimicked instance with such a member. -* Otherwise, when a setup of `x` itself matches, the helper works like the function's own `call`, `apply` and `bind`: it answers what `x(...arguments)` answers, the configured value (a mimicked function or a `mimicks()` function gets the first argument as `this`). -* When nothing is configured for either, the first argument decides. When it is `undefined`, `null`, an object or a function, as in a wrapper's `fn.apply(this, args)` or `fn.call(undefined, ...args)`, the invocation returns the same auto-substitute that `x(...arguments)` returns. So a wrapper that forwards a call gets the nested setups made on `x(...arguments)`, and the calls made on what it returned are checked there (see [What counts as a call](#what-counts-as-a-call)). When it is a string, a number, a boolean, a bigint or a symbol, as in an RPC client's `rpc.call('getUser', 1)` or ioredis' `redis.call('get', 'session')`, no function's `call` or `apply` is meant, so the invocation returns an auto-substitute of its own, one for each list of arguments as they are (`@Substitute.rpc.call('getUser', 1)`). - -Either way, the invocation is recorded once and counts in both meanings: as a call of the member (`x.received().call('getUser', 1)`) and as a direct call of `x` (`x[received]()(1)`, or `sub.received().method(1)` when `x` is `sub.method`). `String(sub)` and failure messages show it once, for example `rpc(1) via .call('getUser', 1)`. A setup written through `call`, `apply` or `bind` only configures the member: `client.rpc.call('getUser', 1).returns(user)` does not answer `client.rpc.call('deleteUser', 1)` or `client.rpc(1)`, and `api.getUser.apply(null, [1]).returns('via apply')` answers that invocation only, not `api.getUser(1)` or `api.getUser.apply(api, [1])`. That goes for setups with matchers through `call` and `apply`, and for those in the `configure` view, too. - -```js -const { Substitute, received } = require('@fluffy-spoon/substitute') - -// an RPC client with a member called call -const client = Substitute.for() -client.rpc.call('getUser', 1).returns({ name: 'ann' }) -console.log(client.rpc.call('getUser', 1)) // prints { name: 'ann' } -client.rpc.received(1).call('getUser', 1) -// the same invocation, read as rpc(1) with 'getUser' as this -client.received(1).rpc(1) - -// a function substitute that a helper calls through apply() -const once = fn => { - let done = false - return function (...args) { - if (!done) { - done = true - return fn.apply(this, args) - } - } -} -const listener = Substitute.for() -listener('saved').returns('ack') -console.log(once(listener)('saved')) // prints ack -listener[received](1)('saved') -``` - -A nested setup or a check through an unconfigured `call` or `apply` is different: it goes through what the invocation returns. With `undefined`, `null`, an object or a function as the first argument, that is the auto-substitute of the direct call: `api.getUser.call(null, 2).name.returns('nested')` makes `api.getUser(2).name` answer `'nested'`, and `api.getUser.apply(null, [3]).received(1).save('x')` checks the calls of `api.getUser(3)`. With a primitive first argument, it is the invocation's own auto-substitute, so the methods of an RPC client stay apart: after `client.rpc.call('getUser', 1).name.returns('ann')`, `client.rpc.call('deleteUser', 1).name` is an auto-substitute, `client.rpc.call('getUser', 1) !== client.rpc.call('deleteUser', 1)`, and a check through one of them counts the calls made on what that one returned. A setup of the direct call still answers such an invocation, though: after `redis('session').returns('cached')`, `redis.call('get', 'session')` returns `'cached'`. When a setup answers an invocation through `call` or `apply` with a substitute, a setup or check in the same expression goes on from that substitute and leaves the invocation out, as for a direct call (see [Which calls lead to a setup or a check](#which-calls-lead-to-a-setup-or-a-check)): after `api.getUser(1).returns(user)`, the setup `api.getUser.call(api, 1).name.returns('ann')` makes `user.name` answer `'ann'` and records no call of `getUser(1)`, and after the code's `api.getUser.apply(api, [1]).save()`, `api.getUser.call(api, 1)[received](1).save()` and `api.received(1).getUser(1)` pass. Checks through a call with matchers count such calls under both meanings, and checks through a concrete call written with `call` or `apply`, such as `rpc.call('getUser', 2).received(1).save()`, narrow as checks through a direct call do when a setup with matchers shares the substitute (see [Through a call with matchers](#through-a-call-with-matchers)). - -An API whose own `call` takes an object first, as web3's `contract.methods.balanceOf(owner).call({ from })` does, is read as a function's `call`: `method.call({ from: 'a' })` and `method.call({ from: 'b' })` are both the call `method()`, so when nothing is configured, they share its auto-substitute, and a nested setup through one of them answers the other, too. Three ways keep them apart: configure the call in the `configure` view, `method[configure]().call({ from: 'a' }).value.returns(2)`; return a substitute of your own, `method.call({ from: 'a' }).returns(result)`; or set it up with a matcher, `method.call(Arg.is(options => options.from === 'a')).value.returns(3)`. Each of them makes `method.call({ from: 'a' })` return a value of its own. - -```js -const { Substitute, Arg, configure, received } = require('@fluffy-spoon/substitute') - -const api = Substitute.for() -api.getUser.call(null, 2).name.returns('nested') -console.log(api.getUser(2).name) // prints nested - -// an RPC client's own call(method, ...params): each method gets an auto-substitute of its own -const client = Substitute.for() -client.rpc.call('getUser', 1).name.returns('ann') -console.log(client.rpc.call('getUser', 1).name) // prints ann -console.log(String(client.rpc.call('deleteUser', 1).name)) // prints @Substitute.rpc.call('deleteUser', 1).name -// the code under test -client.rpc.call('getUser', 1).save() -client.rpc.call('deleteUser', 1).save() -client.rpc.call('getUser', Arg.any())[received](1).save() -client.rpc(Arg.any())[received](2).save() - -// a setup of the direct call still answers -const redis = Substitute.for() -redis('session').returns('cached') -console.log(redis.call('get', 'session')) // prints cached - -// an object first: the call method() for every { from }, unless one of them is configured -const method = Substitute.for() -method.call({ from: 'a' }).value.returns(1) -console.log(method.call({ from: 'b' }).value) // prints 1 -const other = Substitute.for() -other[configure]().call({ from: 'a' }).value.returns(2) -console.log(other.call({ from: 'a' }).value) // prints 2 -console.log(String(other.call({ from: 'b' }).value)) // prints @Substitute().value -``` - -* `x.bind(thisArg, ...arguments)` itself only counts as a call of a member called `bind`. Calling the function it returns is a direct call of `x`, with the bound arguments first. `.returns()` on the result of `x.bind(...)` configures the member `bind`. -* `x.apply(thisArg, value)` with a primitive `value` only has the member meaning, because a function's `apply` would throw. `x.apply(thisArg)` and `x.call()` are the call `x()`. -* On a member called `received` or `didNotReceive`, `queue.received.call(null, 1)` only has the member meaning, and gives the auto-substitute of that invocation (`@Substitute.received.call(null, 1)`), because the direct call `queue.received(1)` would be a check. -* A member `call`, `apply` or `bind` configured as a property (`sub[configure]().call.returns(value)`) reads as that value. A substitute that mimicks an object without such a member reads it as `undefined`, like the object. -* In the `configure` view, `call`, `apply` and `bind` are ordinary members. - -# The symbol API -All of these are exported from the package root. - -| Symbol | Usage | Notes | -|---|---|---| -| `received` | `sub[received](count?).member...` | Always a check. | -| `didNotReceive` | `sub[didNotReceive]().member...` | Always a check, the same as `[received](0)`. | -| `clearReceivedCalls` | `sub[clearReceivedCalls]()` | Symbol only. See [Clearing received calls](#clearing-received-calls). | -| `mimick` | `sub[mimick](instance)` | Symbol only. In TypeScript, a partial instance of an object type is enough. See [Partial mocks](#partial-mocks). | -| `configure` | `sub[configure]().member...` | Symbol only. See [Re-configuring a call](#re-configuring-a-call-configure). | -| `returns`, `throws`, `resolves`, `rejects`, `mimicks` | `sub.member(...)[returns](value)`, `sub.property[throws](error)` | The same as the string methods. They configure a member or a call, so using them on the substitute itself (`sub[returns](1)`) is an error. | - -The symbols are registered with `Symbol.for()`, so they also work when two copies of the package are installed, or loaded twice, as after `jest.resetModules()`. - -Substitutes of two such copies work together as well. A substitute of one copy among the arguments of a substitute of the other is shown by its path in failure messages and printouts, `use(@Substitute)` or `use(@Substitute.child)`, as a substitute of the same copy is, and a failure message that numbers its substitutes numbers those of both copies (see [received and didNotReceive](#received-and-didnotreceive)): with `app` from one copy and `plugin` from the other, after `app.events.subscribe(plugin.handler)`, `app.events.received(1).subscribe(app.handler)` expects `subscribe(@Substitute#1.handler)` and lists `@Substitute#1.events.subscribe(@Substitute#2.handler)`. For that, the copies share one object: an object on the global object, under the registered symbol `Symbol.for('@fluffy-spoon/substitute:guard')` (not enumerable), which the first copy creates and the others find. It says when any of them prints or compares values, and when a matcher of any of them looks at a value, it holds the numbers of the message being built, and it notes the functions that `.bind()` made from their substitutes, which are no substitutes (see [Through a call with matchers](#through-a-call-with-matchers)); a copy of an earlier version does not note those. So what an `Arg.is()` predicate of one copy does to a substitute of the other is treated as with one copy (see [Matching specific arguments](#matching-specific-arguments)): in a check, it leaves no trace, and when a call is compared with the setups, it leaves none on the substitutes of the other copy among the call's arguments, while it is recorded on those that are not among them. (A copy of a development build made before this version leaves the substitutes of its own unnumbered, and records what a predicate of the other copy does to them when a call is compared with the setups, also when they are among the call's arguments; some older builds do so in checks, too.) A check [through a call with matchers](#through-a-call-with-matchers) counts the substitutes of the other copy that the matching calls answered, too. So the reads that Node.js makes while one copy prints or compares an object that inherits from a substitute of the other, such as an instance of `class Plugin extends sdk.Base` (Node.js looks for `href`, `protocol` and `auth`), are not recorded on that substitute, as with one copy (see [Classes that extend a substitute](#classes-that-extend-a-substitute)). Where the global object cannot take that property, because it is frozen, sealed or not extensible, each copy keeps such an object of its own: then such reads are recorded, a substitute of the other copy is printed in full, with its calls and setups, and it is not numbered. - -# Special members -A few members are handled by the substitute itself and cannot be configured or checked: - -* `then` is always `undefined`, so a substitute is not a thenable. You can return it from an `async` function or `await` it, and you get the substitute back. In TypeScript, a member called `then` is typed `never`. -* `util.inspect.custom`: `util.inspect(sub)` and `console.log(sub)` show the substitute's setups and received calls (see [Printing a substitute](#printing-a-substitute)). -* `toJSON`: `JSON.stringify(sub)` gives the same text. A substitute that mimicks an object gives what `JSON.stringify(instance)` gives instead: the result of the instance's own `toJSON()`, or its fields (see [Partial mocks](#partial-mocks)). -* `Symbol.toPrimitive`: converting a substitute to a primitive, as `String(sub)`, template strings, `+`, `==` and comparisons do, gives the same text as well, unless `toString()` or `valueOf()` is configured or mimicked (see below). - -```typescript -import { Substitute } from '@fluffy-spoon/substitute' - -interface Calculator { add(a: number, b: number): number } - -const calculator = Substitute.for() -async function load() { return calculator } -load().then(loaded => console.log(loaded === calculator)) // prints true -``` - -When the substitute configures `toString()` or `valueOf()`, or mimicks an object that has them, converting it to a primitive follows JavaScript's rules instead of giving the printout. A mimicked instance's own `Symbol.toPrimitive`, such as a `Date`'s, is used as it is. Otherwise, `toString()` and `valueOf()` are tried in the order that the conversion asks for: `toString()` first for template strings and `String()`, `valueOf()` first for `+`, `==` and comparisons. Each of them counts only when a call setup matches `()`, a property setup gives a function, or the mimicked instance has a method of its own (not the one of `Object.prototype` or `Function.prototype`), and the first one that gives a primitive wins. When none does, as with a setup for other arguments (`toString(16)`), a configured value that is not a primitive, or a mimicked plain object, the conversion gives the printout. Such a conversion is a call of `toString()` or `valueOf()`, recorded like any other, so `id.received(2).toString()` below counts the template string and the `+`. `util.inspect()`, `console.log()` and failure messages always show the printout. `Symbol.toPrimitive` itself cannot be configured: configure `toString()` or `valueOf()`, or mimick an object. - -```js -const { Substitute, mimick } = require('@fluffy-spoon/substitute') - -const id = Substitute.for() -id.toString().returns('u1') -console.log(`user ${id}`) // prints user u1 -console.log(id + '!') // prints u1! -id.received(2).toString() - -const money = Substitute.for() -money.valueOf().returns(5) -console.log(money + 1, money > 3) // prints 6 true - -const price = Substitute.for() -price[mimick]({ valueOf() { return 5 }, toString() { return '5 EUR' } }) -console.log(price + 1, `${price}`) // prints 6 5 EUR - -const date = Substitute.for() -date[mimick](new Date(0)) -console.log(+date) // prints 0 -``` - -JavaScript, Node.js and test libraries read some members to find out what a value is. Unless you configure them, these read as `undefined` on every substitute and auto-substitute, and the reads are not recorded: - -* `Symbol.iterator`, `Symbol.asyncIterator`, `Symbol.hasInstance`, `Symbol.isConcatSpreadable`, `Symbol.match`, `Symbol.matchAll`, `Symbol.replace`, `Symbol.search`, `Symbol.split`, `Symbol.species`, `Symbol.toStringTag` and `Symbol.unscopables`, -* `util.promisify.custom`: both `Symbol.for('nodejs.util.promisify.custom')` and the running Node.js' own `require('util').promisify.custom`, which is a different symbol on Node.js 10.0 to 12.16.1 and 13.0 to 13.11, -* `asymmetricMatch`, which jest reads to find asymmetric matchers, -* `_isMockFunction`, which the printing of jest and vitest (`pretty-format`) reads to find mock functions, and vitest's spy assertions, too, -* `calledWithExactly`, which sinon-chai reads (with `getCall`) to find sinon spies, -* `handleEvent`, which `addEventListener()` reads to find event listener objects. - -So `[].concat(sub)` keeps the substitute as one element, `value instanceof sub.SomeClass` is `false`, `'text'.startsWith(sub.prefix)` works, `util.promisify(sub.readFile)` calls the substitute on every supported Node.js version (so a `mimicks()` setup that calls the callback works), `Object.prototype.toString.call(sub)` is `'[object Function]'`, jest's `toEqual(sub)` and `toHaveBeenCalledWith(sub)` compare a substitute by identity, like any other function (but see [Test runners](#test-runners) for jest's `toHaveProperty()`), jest and vitest snapshots show a substitute as a function, not as a mock function, the spy assertions of vitest and sinon-chai throw for a substitute instead of passing (jest's do not; see [Test runners](#test-runners)), and a function substitute used as an event listener is called itself (see [Substitutes are functions](#substitutes-are-functions)). A substitute is not iterable: `[...sub]`, `for...of`, `for await...of` and `Promise.all(sub)` throw a `TypeError`. - -`__esModule` is not one of these members. Unconfigured, it reads as an auto-substitute, which counts as `true`, and the read is recorded, as for any other member. So code compiled from ES modules takes a substitute that stands in for a whole module for the module's namespace; see [Mocking a whole module](#mocking-a-whole-module). - -Unlike `then`, these members can be configured, through the `configure` view or by mimicking an instance that has them. The plain `sub[Symbol.iterator]().returns(...)` does not work, because the read gives `undefined`. - -```js -const { Substitute, configure, mimick } = require('@fluffy-spoon/substitute') - -const empty = Substitute.for() -console.log([].concat(empty).length) // prints 1 -const spread = () => [...empty] -spread() // throws TypeError - -const numbers = Substitute.for() -numbers[configure]()[Symbol.iterator]().mimicks(() => [1, 2][Symbol.iterator]()) -console.log([...numbers]) // prints [ 1, 2 ] - -const letters = Substitute.for() -letters[mimick](['a', 'b']) -console.log([...letters]) // prints [ 'a', 'b' ] - -const tagged = Substitute.for() -tagged[configure]()[Symbol.toStringTag].returns('Tagged') -console.log(Object.prototype.toString.call(tagged)) // prints [object Tagged] -``` - -## Substitutes are functions -Every substitute and every auto-substitute is a function: `typeof sub` is `'function'`. And every member that is not configured reads as an auto-substitute, which is a function, too, and counts as `true`. So code under test that asks whether it got a function or an object, or whether an optional member or callback exists (`typeof x === 'function'`, `if (options.onDone)`, `typeof x.method === 'function'`, an options object or a callback as the last argument), takes the branch for a function, or for a member that exists, when it gets a substitute. Only the members listed above read as `undefined`. Configure or mimick what such code should see, or pass it a plain object. - -This also decides what `addEventListener()` does with a substitute: it calls it as a function. Node.js' `EventTarget` and jsdom do so because it is a function, and happy-dom because its `handleEvent` reads as `undefined`. A function substitute added as an event listener therefore records each event as a call of itself, and you check it as such: `onSave.received(1)(Arg.any())`. A substitute that stands in for an event listener object (an object with a `handleEvent` method) is called as a function as well, so its `handleEvent` is not called (in Node.js and jsdom, not even when it is configured). Hand the code under test a plain object that passes the events on to the substitute instead, and configure `handleEvent` on the substitute: code that calls `listener.handleEvent(event)` on a substitute where it is neither configured nor mimicked gets `TypeError: listener.handleEvent is not a function`. - -```js -const { Substitute, Arg, configure } = require('@fluffy-spoon/substitute') - -// the code under test -const watch = (target, listener) => target.addEventListener('save', listener) - -const target = new EventTarget() -const onSave = Substitute.for() -watch(target, onSave) -target.dispatchEvent(new Event('save')) -onSave.received(1)(Arg.any()) - -// an event listener object -const listener = Substitute.for() -listener[configure]().handleEvent(Arg.any()).returns(undefined) -watch(target, { handleEvent: event => listener.handleEvent(event) }) -target.dispatchEvent(new Event('save')) -listener.received(1).handleEvent(Arg.any()) - -const options = Substitute.for() -console.log(typeof options.onDone, Boolean(options.onDone)) // prints function true -``` - -## Printing a substitute -`String(sub)`, template strings, `util.inspect(sub)`, `console.log(sub)` and `JSON.stringify(sub)` show the received calls and the setups of a substitute (`String()` and template strings only when `toString()` and `valueOf()` are neither configured nor mimicked, and `JSON.stringify()` only when the substitute does not mimick an object; see [Special members](#special-members)). An auto-substitute shows its path, such as `@Substitute.logger`, `@Substitute.getUser(1)` or `@Substitute.a.b('x').c`, followed by its own received calls and setups, if it has any. A substitute also lists those of its auto-substitutes, under their paths: the calls in the order they were made, the setups in the order they were configured. A read of a member, like `logger` before `logger.info('started')`, is a received call of its own, so it is listed, too. The calls of a substitute that a setup with matchers shares are listed under the call that it was returned to, `to('room-a').emit('message', 1)`, when there is one such call (see [Through a call with matchers](#through-a-call-with-matchers)). In a failure message, in the printout of another substitute and in a path, an auto-substitute shows only its path, as in `emit('created', @Substitute.child)`, also one of another copy of the package (see [The symbol API](#the-symbol-api)). A call made with `new` shows as `new Client('https://api')`. - -```js -const { Substitute } = require('@fluffy-spoon/substitute') - -const app = Substitute.for() - -// the code under test -app.logger.info('started') -app.save({ id: 1 }) - -app.logger.level.returns(3) -app.getUser(1).name.returns('ann') - -const printedApp = [ - '@Substitute {', - ' received:', - ' logger', - " logger.info('started')", - ' save({ id: 1 })', - ' configured:', - ' logger.level => returns(3)', - " getUser(1).name => returns('ann')", - '}' -] -console.log(String(app) === printedApp.join('\n')) // prints true - -const logger = app.logger -const printedLogger = [ - '@Substitute.logger {', - ' received:', - " info('started')", - ' configured:', - ' level => returns(3)', - '}' -] -console.log(String(logger) === printedLogger.join('\n')) // prints true - -console.log(`${app.getUser(2)}`) // prints @Substitute.getUser(2) -console.log(JSON.stringify({ user: app.getUser(2) })) // prints {"user":"@Substitute.getUser(2)"} -``` - -Printing always ends, also for values that refer to each other: - -* A path can hold other paths, among the arguments of its calls. Such an inner path shows its own arguments only when they are all primitives: `@Substitute.save(@Substitute.getUser(1))`, but `@Substitute.wrap(@Substitute.save(…))` for `app.wrap(app.save({ id: 1 }))`. -* A call whose arguments are already being printed further out shows them as `(…)`. That happens when the code under test stores what a factory makes on the object it passes to the factory, or binds handlers to the instance that holds them: with `context.child = app.create(context)`, `String(context.child)` is `@Substitute.create({ name: 'root', child: @Substitute.create(…) })`. -* The printout of a substitute lists all of its own received calls and setups, and at most 50 received calls and 50 setups of its auto-substitutes. A list that leaves some out ends with `… and N more`. -* A path with more than 10 members shows the first 3 and the last 6: `@Substitute.next.next.next.….next.next.next.next.next.next`. Printing, `JSON.stringify()`, `in` and [`[clearReceivedCalls]()`](#clearing-received-calls) work on chains of auto-substitutes of any length, such as a linked list walked by the code under test. - -Each value in a failure message, in the printout of a substitute and in a path is printed within bounds, so a large argument takes a few lines: a DOM event that refers to its element, document and window, an object with thousands of keys or a string of a megabyte. Values are printed by `util.inspect()`, two levels deep as it does by default, so `{ a: { b: { c: 1 } } }` shows in full and `{ a: { b: { c: { d: 1 } } } }` shows as `{ a: { b: { c: [Object] } } }` (a failure message prints deeper where that tells the expected call from a received one; see [received and didNotReceive](#received-and-didnotreceive)), and: - -* arrays, `Map`s and `Set`s show their first 20 items (`... 99980 more items`), and objects their first 20 keys (`... 4980 more keys`); -* a string inside another value shows its first 200 characters (`'yyy…'... 9800 more characters`), and a string that is an argument itself up to about 960; -* each value ends after 1,000 characters (`… (N more characters)`), and a call shows at most 20 arguments (`... 980 more arguments`); -* in a path, each argument is shown on one line, without nested objects (`[Object]`), with at most 10 keys or items and at most 200 characters, and a call shows at most 10 arguments: `@Substitute.lookup({ key0: 0, key1: 1, key2: 2, key3: 3, key4: 4, key5: 5, key6: 6, key7: 7, key8: 8, key9: 9, ... 4990 more keys })`. - -Values within these bounds print exactly as `util.inspect(value)` prints them. That includes the other keys of an array, a `Map` or a `Set`, such as the `total` of an array of rows, which follow the items: `[ { id: 1 }, { id: 2 }, total: 10 ]`. (In a `Map` or `Set` with more than 20 entries, they come before `... N more items`, where `util.inspect()` shows them after it.) Matchers inside plain objects and arrays, in setups and in the expected call of a message, are shown by their own label at any depth, with the objects and arrays that hold them: `find({ q: { r: { s: { t: Arg.any{number} } } } }) => returns(2)`. Measured on Node.js 22, a failure message about a function substitute that happy-dom called with one click event takes about 2,100 characters, and with 60 click events about 22,000 characters. The bounds apply to what `util.inspect()` shows. Proxies, objects with a custom inspection of their own, and `Date`s, typed arrays and other built-in objects are shown by `util.inspect()` as they are, without the limit on keys, but still end after 1,000 characters. A revoked proxy shows as `` (where `util.inspect()` can print one; see [How arguments are compared](#how-arguments-are-compared)), and the value that holds it is printed within the bounds. On Node.js 10 to 12.16, whose `util.inspect()` cannot shorten strings, a long string ends after 1,000 characters, too. - -Errors show as `[Name: message]`, without their stack, wherever they appear: as an argument, inside an object, array, `Map` or `Set` argument (one level deeper than other objects, too, so three levels deep: `log({ context: { err: { cause: [Error: deep] } } })`), among the other keys of an array (`[ 1, failure: [TypeError: bad] ]`), and as the value configured with `throws()`. Their own enumerable properties other than `name`, `message` and `stack` follow in braces, and then their `cause`, as `[cause]`: `fail([HttpError: not found] { status: 404 })`, `fail([Error: saving failed] { [cause]: [TypeError: x is undefined] })`. An error shows at most 10 such properties, then `... N more keys`, and each of them briefly: one level deep, in at most 200 characters, with errors among them shown in the same form. Causes are shown three levels deep. A property or a cause with a getter shows as `[Getter]`, and the getter does not run. An error that refers back to itself shows only `[Name: message]` there. - -```js -const { Substitute, Arg } = require('@fluffy-spoon/substitute') - -const app = Substitute.for() -console.log(String(app.save(app.getUser(1)))) // prints @Substitute.save(@Substitute.getUser(1)) -console.log(String(app.wrap(app.save({ id: 1 })))) // prints @Substitute.wrap(@Substitute.save(…)) - -// the code under test stores what a factory makes on the object it passes to the factory -const context = { name: 'root' } -context.child = app.create(context) -console.log(String(context.child)) // prints @Substitute.create({ name: 'root', child: @Substitute.create(…) }) - -let node = Substitute.for() -for (let i = 0; i < 20; i++) node = node.next -console.log(String(node)) // prints @Substitute.next.next.next.….next.next.next.next.next.next - -const repository = Substitute.for() -repository.save(new Error('saving failed', { cause: new TypeError('x is undefined') })) -repository.load(1).throws(new RangeError('too large')) -repository.find({ where: { name: { startsWith: Arg.any('string') } } }).returns([]) -const printedRepository = [ - '@Substitute {', - ' received:', - " save([Error: saving failed] { [cause]: [TypeError: x is undefined] })", - ' configured:', - ' load(1) => throws([RangeError: too large])', - ' find({ where: { name: { startsWith: Arg.any{string} } } }) => returns([])', - '}' -] -console.log(String(repository) === printedRepository.join('\n')) // prints true - -class HttpError extends Error { - constructor(message, status) { - super(message) - this.name = 'HttpError' - this.status = status - } -} - -const logger = Substitute.for() -logger.error('request failed', new HttpError('not found', 404)) -logger.warn({ cause: new SyntaxError('bad json') }) -logger.info({ context: { err: { cause: new Error('deep') } } }) -logger.debug({ a: { b: { c: 1 } } }) -logger.debug({ a: { b: { c: { d: 1 } } } }) -logger.trace(...Array.from({ length: 25 }, (_, i) => i)) -const printedLogger = [ - '@Substitute {', - ' received:', - " error('request failed', [HttpError: not found] { status: 404 })", - " warn({ cause: [SyntaxError: bad json] })", - " info({ context: { err: { cause: [Error: deep] } } })", - ' debug({ a: { b: { c: 1 } } })', - ' debug({ a: { b: { c: [Object] } } })', - ' trace(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ... 5 more arguments)', - '}' -] -console.log(String(logger) === printedLogger.join('\n')) // prints true - -const table = Object.fromEntries(Array.from({ length: 5000 }, (_, i) => [`key${i}`, i])) -console.log(String(logger.lookup(table))) // prints @Substitute.lookup({ key0: 0, key1: 1, key2: 2, key3: 3, key4: 4, key5: 5, key6: 6, key7: 7, key8: 8, key9: 9, ... 4990 more keys }) - -// the other keys of an array follow its items, also when it is long -const failures = Object.assign(Array.from({ length: 1001 }, (_, i) => new Error(`failed ${i}`)), { total: 1001 }) -const jobs = Substitute.for() -jobs.retry(failures) -console.log(String(jobs).includes('total: 1001')) // prints true -``` - -jest and vitest print a function, and so a substitute, with its `name` member, which is a member of the substitute like any other: `expect(...)` failure messages and diffs show `app.logger` as `[Function @Substitute.logger.name]` (or as the value that `name` is configured to return). Their snapshots (`toMatchSnapshot()`, `toMatchInlineSnapshot()`) show every function as `[Function]`, so a substitute, too. To find out what a value is, their printing reads members of it, such as `$$typeof`, `constructor`, `nodeType` and `name`, and these reads are recorded and listed in printouts of the substitute. It does not take a substitute for a mock function, because `_isMockFunction` reads as `undefined` (see [Special members](#special-members)). - -Tools that print without the custom inspection that the library provides, such as the messages of `node:assert`, show any substitute as `[Function: bound substitute]` (on Node.js 26 as `Proxy([Function: bound substitute])`; Node.js 10 reads the `name` member and shows `[Function: @Substitute.name]`). - -A function that takes over the prototype of a substitute or of a bound method of one is an ordinary function, not a substitute: it prints as a function, printing it does not call it, and nothing is recorded. Such functions are the wrappers that `mem`, `p-memoize`, `debounce-fn` and `onetime` (through `mimic-fn`) and `util.promisify()` make, and functions bound with the function's own `bind`: `Function.prototype.bind.call(listener, context)`, and wrappers bound again, such as `mem(api.getUser.bind(api)).bind(null, 1)` or `util.promisify(fs.readFile).bind(null, path)`. `util.inspect()`, `console.log()` and failure messages show these as `[Function: bound ]`, `[Function: bound bound getUser]` and `[Function: bound readFile]`. A wrapper that copies the `name` of the function that it wraps, as `mimic-fn` and `util.promisify()` do, gets the member's name, as for a real method: `mem(api.getUser)` prints as `[Function: getUser]`, and `mem(api.getUser.bind(api))` as `[Function: bound getUser]` (see [Freezing, defined properties and `in`](#freezing-defined-properties-and-in) for the `name` of a substitute). The function's own `bind` reads the `length` and `name` members of the function that it binds, so `Function.prototype.bind.call(listener, context)` records these two reads on `listener`, as reads of the code under test. - -```js -const util = require('util') -const { Substitute, Arg } = require('@fluffy-spoon/substitute') - -// what mimic-fn does for the function that a memoizing wrapper wraps -const mimic = (wrapper, wrapped) => { - Object.defineProperty(wrapper, 'name', Object.getOwnPropertyDescriptor(wrapped, 'name')) - return Object.setPrototypeOf(wrapper, Object.getPrototypeOf(wrapped)) -} - -const api = Substitute.for() -api.getUser(1).returns({ id: 1 }) -// the code under test memoizes a method of its client -const getUser = mimic(function memoized(id) { return api.getUser(id) }, api.getUser) -console.log(getUser(1)) // prints { id: 1 } -console.log(util.inspect(getUser)) // prints [Function: getUser] -api.received(1).getUser(1) - -// the code under test binds a listener with the function's own bind -const listener = Substitute.for() -const bound = Function.prototype.bind.call(listener, { id: 1 }) -console.log(util.inspect(bound)) // prints [Function: bound ] -listener.didNotReceive()(Arg.all()) -``` - -## Freezing, defined properties and `in` -`Object.freeze()`, `Object.seal()` and `Object.preventExtensions()` work on a substitute and on an auto-substitute, and it keeps working afterwards: reads, calls, `new`, setups, checks and printing work as before, and `Object.isFrozen()`, `Object.isSealed()` and `Object.isExtensible()` say what was done. So code under test that freezes what it is given, like `this.options = Object.freeze(options)`, works with a substitute. - -`Object.defineProperty(sub, key, descriptor)` defines a real property of the substitute. Reads return its value (a getter runs with the substitute as `this`), assignments write it (or fail, if it is not writable), and `delete` removes it (if it is configurable), after which the key is an ordinary member again. Reads and assignments of such a property are not recorded, and the property has no setup API. On a substitute that mimicks an object, `Object.defineProperty()` defines the member on the instance instead, as an assignment writes to it, and `delete sub.key` deletes the instance's member (see [Partial mocks](#partial-mocks)); a descriptor with `configurable: false`, a descriptor without `configurable` for a key that the instance does not have as its own (the default is then `false`, as on any object), and one that the instance refuses (a frozen instance) define a property of the substitute, as above, and the substitute then keeps its own keys, as below. +--- -Like every function, a substitute has the own properties `length` and `name`, which are not enumerable: `Reflect.ownKeys(sub)` and `Object.getOwnPropertyNames(sub)` are `[ 'length', 'name' ]`, while `Object.keys(sub)`, `{ ...sub }`, `Object.assign({}, sub)`, `for...in` and `JSON.stringify(sub)` do not see them. Auto-substitutes, the values that the library hands out for checks and setups, and functions returned by `x.bind(...)` have them as well. Both are read-only and configurable. `length` is `0`, and `name` is the member's name for a member (`'getKey'` for `keys.getKey`, `'[description]'` for a member with a symbol key), `'bound getKey'` for `keys.getKey.bind(keys)`, and `''` for a substitute itself and for the result of a call. These are what tools that adapt or wrap a function read: `util.callbackify(keys.getKey)` works, and wrappers that copy the name of the function that they wrap get the member's name (see [Printing a substitute](#printing-a-substitute)). Reading `sub.name` or `sub.length` does not use them: these are members like any other, so the read is recorded and gives an auto-substitute unless the member is configured (after `sub.name.returns('billing')`, `sub.name` is `'billing'`, while the own property `name` still holds `''`), and `'name' in sub` is `false` unless it is configured. `delete sub.member` changes nothing (unless the substitute mimicks an object, see above). - -A substitute that mimicks an object lists the instance's enumerable own keys before `length` and `name` (see [Partial mocks](#partial-mocks)). A substitute that is given a property of its own lists the properties defined on it, followed by `length` and `name`: `[ 'version', 'length', 'name' ]` (a mimicked instance's keys are then no longer listed, and later `Object.defineProperty()` calls define properties of the substitute; on a substitute that mimicks an object, that happens only for a property defined with `configurable: false` or without `configurable` for a new key, or on a frozen instance; reads, calls and checks of the instance's members work as before). A substitute that is frozen, sealed or made non-extensible lists only the properties defined on it, without `length` and `name`, so `Reflect.ownKeys()` gives `[]` for one that has none. On Node.js 12 and newer, `util.callbackify()` of such a substitute throws a `TypeError`, because it reads the descriptor of `length`: `Cannot read properties of undefined (reading 'value')` from Node.js 16.9 on, and `Cannot read property 'value' of undefined` before (Node.js 10 does not read it). Wrap such a substitute in a function: `util.callbackify((...args) => frozen(...args))`. Its auto-substitutes are not frozen, so `util.callbackify(frozen.load)` works. - -The values that the library hands out for checks and setups (`sub[received]()`, `sub[configure]()` and members of them), a function returned by `x.bind(...)` and a member configured both as a property and as a method cannot be frozen, sealed or given properties: `Object.freeze()`, `Object.seal()`, `Object.preventExtensions()` and `Object.defineProperty()` throw a `SubstituteException` that says so. - -`Object.setPrototypeOf(sub, prototype)` works on a substitute, a function substitute and an auto-substitute (`Object.setPrototypeOf(app.events, EventEmitter.prototype)`), for code under test that checks `instanceof`: `sub instanceof EventEmitter` is then `true`. Reads, calls, assignments (which are recorded, as on any substitute), setups, checks, the symbols and their views, `new`, `String()`, template strings and `JSON.stringify()` work as before, and so does passing the substitute as an argument or configuring it as a value. Only `util.inspect()` no longer finds the library's custom inspection, which it looks up through the prototype: `util.inspect(sub)` and `console.log(sub)` show `[Function: bound substitute] EventEmitter` (on Node.js 26 inside `Proxy(...)`), and so do failure messages and printouts in which the substitute is an argument (`use([Function: bound substitute] EventEmitter)`, where other substitutes show as `@Substitute`). Objects that inherit from such a substitute are ordinary objects, as above. - -The prototype of a frozen, sealed or non-extensible substitute cannot change, as with any object that is not extensible: `Object.setPrototypeOf()` throws a `TypeError` that names the substitute, `@Substitute.events is not extensible: its prototype cannot be changed after Object.freeze(), Object.seal() or Object.preventExtensions()`, and setting the prototype it already has succeeds. Unlike on an ordinary object, `Reflect.setPrototypeOf()` throws that `TypeError`, too, instead of returning `false`, because a proxy cannot tell the two apart. (`sub.__proto__ = value` does not set the prototype: it is an assignment of a member called `__proto__`, recorded like any other.) `Object.defineProperty()` of a new key throws a `TypeError` on such a substitute as well, as on any object that is not extensible, with the message that V8 gives for proxies: `'defineProperty' on proxy: trap returned falsish for property 'x'`. - -`key in sub`, and `Reflect.has(sub, key)`, is `true` when the key has a setup on the substitute: a property setup, a call setup, or a setup further down, like `sub.config.port.returns(80)` for `'config'`. It is also `true` when the substitute mimicks an instance that has the key (`key in instance`, so inherited members count), and for a property defined with `Object.defineProperty()`. Otherwise it is `false`: for members that the code under test used but that are not configured, for the members every function has (`call`, `apply`, `bind`, `name`, `length`, ...), for `then`, `toJSON` and the protocol members above (unless they are configured), and for the library's own methods. Reads, calls and checks through a call with a matcher, like `app.repo(Arg.any()).received(1).save(1)` (see [Through a call with matchers](#through-a-call-with-matchers)), do not count as setups here. `in` records nothing, and it takes the same time however many auto-substitutes the substitute has. So code under test that checks whether an optional member exists, like `if ('destroy' in stream)`, takes the branch that the test configured. - -```js -const { Substitute, configure } = require('@fluffy-spoon/substitute') +```typescript +import { Substitute, Arg } from '@fluffy-spoon/substitute' -// the code under test freezes its options, and checks for an optional member -class Service { - constructor(options, stream) { - this.options = Object.freeze(options) - this.stream = stream - } - get name() { return this.options.name } - close() { return 'destroy' in this.stream ? this.stream.destroy() : this.stream.end() } +interface Mailer { + send(to: string, subject: string): boolean } -const options = Substitute.for() -options.name.returns('billing') -const stream = Substitute.for() -stream.destroy().returns('destroyed') - -const service = new Service(options, stream) -console.log(service.name) // prints billing -console.log(Object.isFrozen(options)) // prints true -console.log(service.close()) // prints destroyed -console.log('end' in stream) // prints false - -const versioned = Substitute.for() -Object.defineProperty(versioned, 'version', { value: 2, enumerable: true, configurable: true }) -console.log(versioned.version, Object.keys(versioned)) // prints 2 [ 'version' ] -console.log(Reflect.ownKeys(versioned)) // prints [ 'version', 'length', 'name' ] -versioned.didNotReceive().version -console.log(Reflect.ownKeys(Substitute.for())) // prints [ 'length', 'name' ] -console.log(Reflect.ownKeys(Object.freeze(Substitute.for()))) // prints [] - -Object.freeze(versioned[configure]()) // throws SubstituteException: cannot be used on -``` - -On a substitute that mimicks an object, a new key defined with the default attributes is the substitute's own, as on a plain object: +const mailer = Substitute.for() +mailer.send(Arg.any(), 'Welcome!').returns(true) -```js -const { Substitute, mimick } = require('@fluffy-spoon/substitute') - -const config = { port: 80 } -const settings = Substitute.for() -settings[mimick](config) +console.log(mailer.send('ann@example.com', 'Welcome!')) // prints true -// without configurable: true, a new key is a property of the substitute, which cannot be redefined -Object.defineProperty(settings, 'loaded', { value: true }) -console.log(Object.prototype.hasOwnProperty.call(settings, 'loaded'), 'loaded' in config) // prints true false -Object.defineProperty(settings, 'loaded', { value: false }) // throws TypeError: trap returned falsish -// the instance's members still work -console.log(settings.port) // prints 80 -settings.received(1).port +mailer.received(1).send('ann@example.com', Arg.any()) +mailer.didNotReceive().send('bob@example.com', Arg.any()) ``` -```js -const util = require('util') -const { Substitute, Arg } = require('@fluffy-spoon/substitute') - -const keys = Substitute.for() -keys.getKey(Arg.any()).resolves('secret') -console.log(Object.getOwnPropertyDescriptor(keys.getKey, 'name').value) // prints getKey -// a read of the member called name is a read like any other -console.log(typeof keys.getKey.name) // prints function - -// the code under test adapts the method to a callback API -const getKey = util.callbackify(keys.getKey) -getKey('kid', (error, key) => console.log(error, key)) // prints null secret -keys.received(1).getKey('kid') - -const store = Object.freeze(Substitute.for()) -store(Arg.any()).resolves('saved') -util.callbackify(store) // throws TypeError -const save = util.callbackify((...args) => store(...args)) -save('ann', (error, result) => console.log(error, result)) // prints null saved -``` +No `jest.fn()` per method, no `as any`, no real instance needed: you write the call you expect, exactly as the code under test makes it, and the compiler checks it. -```js -const { EventEmitter } = require('events') -const util = require('util') -const { Substitute, Arg, received } = require('@fluffy-spoon/substitute') +## Why substitute.js? -// the code under test only accepts emitters -const subscribe = events => { - if (!(events instanceof EventEmitter)) throw new TypeError('not an emitter') - events.on('saved', () => { }) -} +- **Reads like the code it fakes.** Configure with `sub.method(args).returns(value)` and verify with `sub.received().method(args)`. No stringly-typed method names. +- **Strongly typed.** Argument types, return values and matcher predicates are all inferred from your interface or class, and `strict` mode is fully supported. +- **Fakes from nothing.** Create a substitute for any interface, class, function or constructor type. Every member is faked, so nothing real runs by accident. +- **Partial mocks when you want them.** Hand some or all calls to a real implementation with `mimicks()` or `[mimick]()`. +- **Clear failure messages.** A failed check tells you what was expected, what was received, and where. +- **Works with any test runner.** ava, jest, mocha, `node:test` and vitest are tested on every change. CommonJS, ES modules and the major bundlers are supported. +- **No runtime dependencies.** -const app = Substitute.for() -Object.setPrototypeOf(app.events, EventEmitter.prototype) -subscribe(app.events) -app.events[received](1).on('saved', Arg.any()) -console.log(`${app.events}`.split('\n')[0]) // prints @Substitute.events { -console.log(util.inspect(app.events).includes('[Function: bound substitute] EventEmitter')) // prints true +## Installing -// a frozen substitute keeps its prototype -const options = Substitute.for() -Object.freeze(options) -Object.setPrototypeOf(options, EventEmitter.prototype) // throws TypeError: @Substitute is not extensible: its prototype cannot be changed after Object.freeze() -Reflect.setPrototypeOf(options, EventEmitter.prototype) // throws TypeError: @Substitute is not extensible -console.log(Object.setPrototypeOf(options, Object.getPrototypeOf(options)) === options) // prints true -Object.defineProperty(options, 'x', { value: 1 }) // throws TypeError: 'defineProperty' on proxy +```sh +npm install @fluffy-spoon/substitute --save-dev ``` -# Typing limitations -TypeScript cannot express a few things about substitutes: - -* **Assigning a property on the substitute** (`calculator.isEnabled = true`) does not compile, because the property's type also carries the setup API (`.returns()` and so on). Assign through the interface type, as the code under test does, and check with `calculator.received().isEnabled = true`. The same goes for tools that replace a member and type the replacement by the member's type, such as `sinon.replace(fs, 'stat', fake)` on a mimicked substitute (TS2345, naming `PositionalSignatureOf<...>` and `[returns]`): cast the substitute to the plain interface there, `sinon.replace(fs as Fs, 'stat', fake)`, which is the same call at runtime (see [Test runners](#test-runners)). -* **`null` and `undefined`** are not part of the type of a call or property under `strictNullChecks`, although `.returns(null)` is accepted. Assign the value to the declared type, or give explicit type arguments (`t.is(repository.find(1), null)`). -* **A generic method called with explicit type arguments** (`store.get('answer')`) has no setup API. Call it without type arguments. -* **Generic methods** (`get(key: K): Config[K]`, a typed event emitter's `emit(event: E, ...args: Parameters)`, or Node.js' `EventEmitter` with a `@types/node` version that types the events, which needs TypeScript 4.8 or newer; see the end of this item for which versions) have the setup API, the checks and the `configure` view, with their type parameters replaced by their constraints. So the arguments are checked against the constraints only, and the configured value against what the method returns for them. With `Config` being `{ port: number; host: string }`, `config.get('port').returns('eighty')` compiles, because `Config[keyof Config]` is `number | string`, and `emitter.emit('failed', 'id1')` compiles although `'failed'` takes an `Error`, because the event and its arguments are not matched up. A value that the method can never return is rejected (`config.get('port').returns(Symbol('80'))`, also with `Arg.any()` arguments). That holds as well for arguments that fit the parameters only with the type parameters replaced by their constraints: for `same(a: T, b: T): T`, `same(1, 'x').returns(...)` takes what the method returns for those constraints, `string | number`, and never any value. A call with too many or too few arguments is rejected (`config.get('port', 'extra')`), with two exceptions. One is Node.js' `EventEmitter.emit`, on every version: the number of its arguments depends on the event, so on a substitute, `orders.emit('paid', 'o1')` compiles although `paid` also takes an amount, and so does `Arg.all()` after its last argument (`orders.emit('paid', 'o1', 20, Arg.all())`, where `Arg.all()` matches the empty rest). The other is on TypeScript 3.6 to 3.9: there, a generic method whose rest parameter is typed by an indexed access (`send(event: K, ...args: Events[K])`) takes any number of arguments on a substitute (the interface's own type rejects them). TypeScript 4.0 and newer check them. A generic method whose return type is conditional on a type parameter (`convert(value: T): T extends string ? number : boolean`, or `listeners()` of `EventEmitter`) has the setup API as well, but TypeScript cannot work out that return type for a setup, so `.returns()` takes any value there. A callback without parameter types gets no types from a generic method (TypeScript reports that they implicitly have an `any` type): annotate them, as in `orders.on('paid', (orderId: string, amount: number) => { })`. An `Arg.is()` predicate without a parameter type does get the parameter's type, with the type parameters replaced by their constraints (see [Matching specific arguments](#matching-specific-arguments)), except in a rest parameter whose type depends on a type parameter, such as the event arguments of a typed emitter's `emit()`. There it gets the parameter types of all events together (`string | Error` for `emitter.emit('saved', Arg.is(id => id.startsWith('o')))` with the emitter below), or `unknown` with Node.js' `EventEmitter`, so the call does not compile: give the predicate a parameter type, as in `orders.received(1).emit('paid', Arg.is((orderId: string) => orderId.startsWith('o')), Arg.any())`. With a type parameter used as a key, a call with a matcher takes what the method returns for the key's constraint: `config.get(Arg.is(key => key === 'port')).returns(80)` takes `number | string`, and `.returns(true)` does not compile. On Node.js' `EventEmitter`, `Arg.all()` after the leading arguments of `emit()` compiles, in setups, checks and the `configure` view (`orders.received(1).emit('paid', Arg.all())`, `orders.emit('paid', 'o1', Arg.all()).returns(true)`), and the leading arguments are checked against `emit()`'s own signature: `orders.emit('nope', Arg.all())` and `orders.emit('paid', 1, Arg.all())` do not compile. For the event itself, `emit()` there takes no matcher but `Arg.any()` and `Arg.all()`: `Arg.any('string')` and `Arg.is()`, with or without a parameter type, do not compile in that position. Write the event, or `orders.received(1).emit(Arg.any(), Arg.all())`. What this item says about Node.js' `EventEmitter` holds for the `@types/node` versions that declare `emit(eventName: Key, ...args: Args)`: 18.19.63 and newer 18.x versions, 20.11.21 and newer 20.x versions, 22.x and 24.x. (Older versions have no generic `EventEmitter`, so `EventEmitter` does not compile with them.) From `@types/node` 25 on, `emit()` is declared with `E extends string | symbol`, and on a substitute neither the event nor its arguments are checked: `orders.emit('nope', Arg.all())`, `orders.emit('paid', 1, Arg.all())`, `orders.received(1).emit(Arg.any('string'), Arg.all())` and `orders.emit(Symbol('x'), Arg.all())` compile, an `Arg.is()` predicate without a parameter type gets `any` there (`orders.emit('paid', Arg.is(orderId => orderId.nonexistent), Arg.any())` compiles), and `on()` and `once()` take any listener, whose parameters are `any` when it does not annotate them. `.returns()` still takes only a boolean for `emit()`. TypeScript itself checks less there, too: `new EventEmitter().emit('refunded')` compiles with `@types/node` 25, while `emit('paid', 1)` does not. -* **A type parameter of a generic method that has a default** is replaced by its constraint as well, not by its default. So pino's `child(bindings): Logger`, which returns a `Logger` when it is called without type arguments, is taken as returning `Logger`, and a substitute of `Logger` does not fit that: `log.child(Arg.any()).returns(Substitute.for())` does not compile, also not in the `configure` view (TypeScript reports that `SubstituteOf` is not assignable to `Logger`, which has an index signature that it lacks). Return a substitute of `Logger`, `log.child(Arg.any()).returns(Substitute.for>())`, or cast, `childLogger as unknown as Logger`. Checks are not affected (`log.received(1).child({ module: 'auth' })`). TypeScript 3.6 accepts the `Logger` value. -* **A generic factory method or a generic class used as a constructor substitute:** an unconstrained type parameter is replaced by `unknown`, so a generic factory method (`create(name: string, processor: (job: Job) => Promise): Worker`) or a generic class used as a constructor substitute (`Substitute.for()`) counts as returning `Worker`. When `D` is used contravariantly, as in bullmq's function-typed `processFn` property, a substitute of `Worker<{ userId: string }>` does not fit that, so `.returns(worker)` does not compile, also not in the `configure` view. Cast through `unknown`: `factory.create('digest', Arg.any()).returns(worker as unknown as Worker)`, and `WorkerClass('digest', Arg.any()).returns(worker as unknown as Worker)` for the class. Explicit type arguments (`factory.create<{ userId: string }>(...)`) select the interface's own signature, which has no setup API. No cast is needed when `D` is only used covariantly (`make(value: D): Box` with `Box` being `{ value: D; get(): D }`), or only in the parameters of methods, which TypeScript checks bivariantly. With a constraint (`D extends Payload`), a substitute of `Worker` fits, while one of `Worker<{ userId: string; extra: number }>` needs the cast. -* **Overloads that are generic with constrained type parameters:** the substitute types such overloads with their type parameters replaced by their constraints, and which forms of a setup have the setup API then depends on how the parameter uses the type parameter. Checks take every form (`users.received(1).save(Arg.any())`, `users[received](1).save(Arg.any())`, `s3.received(1).send(Arg.is((command: GetObjectCommand) => command.input.Key === 'k'))`, `s3[received](1).send(new PutObjectCommand({ ... }))`), and so do a method with a single generic signature, generic overloads without constraints and overloads without type parameters. - * **The parameter's type is the type parameter itself** (or an array of it), as in TypeORM's `Repository.save()` and `remove()` (`save>(entities: T[], options?): Promise`, `save>(entity: T, options?): Promise` and the like): a setup with `Arg.any()` (or `Arg.any('object')`) for that argument resolves to the method's own overload, so `users.save(Arg.any()).resolves(user)` does not compile (TS2339: "Property 'resolves' does not exist on type 'Promise'"), and an untyped predicate's parameter is typed for the overload for arrays (`Arg.is(saved => saved.id === 1)` gives TS2339: "Property 'id' does not exist on type 'DeepPartial[]'"). Use `Arg.all()`, which takes what any overload resolves to (`users.save(Arg.all()).resolves(user)` and `.resolves([user])`), a typed predicate (`Arg.is((saved: User) => saved.id === 1)`, `Arg.is((saved: User[]) => saved.length > 0)`), a matcher cast to the parameter type (`Arg.any() as User`, `Arg.any() as User[]`, `Arg.any() as DeepPartial`), or a value (`users.save(user).resolves(user)`). This holds without `strict` as well. The `configure` view takes the first overload that accepts the arguments, the one for arrays with TypeORM: `users[configure]().save(Arg.any()).resolves([user])` compiles, and `.resolves(user)` there does not. Values that no overload resolves to are still rejected (`users.save(Arg.all()).resolves('x')`, `users.save(Arg.any() as User).resolves([user])`). - * **The parameter's type only contains the type parameters**, as in AWS SDK v3's `client.send()` (`send(command: Command<..., InputType, ..., OutputType, ...>)`): it is the other way round, under `strict`. `Arg.any()`, `Arg.any('object')`, `Arg.all()` and an untyped predicate that narrows (`Arg.is(command => command instanceof GetObjectCommand && command.input.Key === 'report.csv')`, also in the `configure` view) have the setup API. A concrete command (`s3.send(new GetObjectCommand({ ... })).resolves(object)`), a typed predicate (`Arg.is((command: GetObjectCommand) => ...)`) and a cast (`Arg.any() as GetObjectCommand`) get the client's own overload (TS2339: "Property 'resolves' does not exist on type 'Promise'"), a type guard (`Arg.is((command): command is GetObjectCommand => ...)`) does not compile (TS2677: "A type predicate's type must be assignable to its parameter's type"), and in the `configure` view, a typed predicate fits no overload (TS2769). The reason is that `Command` is invariant in its type parameters under `strictFunctionTypes`, so plain TypeScript does not assign a `GetObjectCommand` to the `Command` of the constraints either (TS2322). Without `strict` (or `strictFunctionTypes`), every form compiles. Values that no overload resolves to are still rejected (`s3.send(Arg.all()).resolves('x')`, TS2345: "... is not assignable to parameter of type 'ServiceOutputTypes'"). (Checked with typeorm 0.3.31 and `@aws-sdk/client-s3` 3.1173 on TypeScript 3.6, 3.9, 4.5, 5.0, 5.9 and 7.0.2; typeorm's own typings need TypeScript 4.5 or newer.) - * **A `mimicks()` function after `Arg.all()`** on such overloads (see [Ignoring all arguments](#ignoring-all-arguments)) gets its untyped parameters with the type parameters replaced by their constraints, `DeepPartial[] | DeepPartial` for TypeORM, so one that returns its argument does not compile: `users.save(Arg.all()).mimicks(entity => Promise.resolve(entity))` and `users.save(Arg.all()).mimicks(async entity => entity)` fail with TS2322 ("Type 'Promise | DeepPartial[]>' is not assignable to type ..."), although a function assigned to the method itself compiles on TypeScript 4.3 and newer. Annotate the parameter or cast what the function returns: `users.save(Arg.all()).mimicks(async (entity: any) => entity)`, `users.save(Arg.all()).mimicks(entity => Promise.resolve(entity as any))`. - - ```typescript - import { Substitute, Arg, configure, received } from '@fluffy-spoon/substitute' - - // the overloads of TypeORM's Repository.save, in short - type DeepPartial = { [P in keyof T]?: T[P] } - interface User { id: number; name: string } - interface Users { - save>(entities: T[]): Promise<(T & User)[]> - save>(entity: T): Promise - } - const user: User = { id: 1, name: 'ann' } - - const users = Substitute.for() - // Arg.all() takes what any overload resolves to - users.save(Arg.all()).resolves(user) - users.save({ name: 'ann' }).then(saved => console.log(saved.id)) // prints 1 - users.received(1).save(Arg.any()) - users[received](1).save(Arg.any('object')) - - const typed = Substitute.for() - typed.save(Arg.is((saved: User) => saved.id === 1)).resolves(user) - typed.save(Arg.any() as User[]).resolves([user]) - typed[configure]().save(Arg.any()).resolves([user]) - // a value works, too - Substitute.for().save(user).resolves(user) - // @ts-expect-error the call resolves to the method's own overload: Promise, which has no setup API - typed.save(Arg.any()).resolves(user) - // @ts-expect-error the configure view takes the first overload, for arrays - typed[configure]().save(Arg.any()).resolves(user) - // @ts-expect-error no overload resolves to a string - typed.save(Arg.all()).resolves('x') - // @ts-expect-error an untyped predicate's parameter is typed for the overload for arrays - typed.save(Arg.is(saved => saved.id === 1)) - - // a mimicks() function that returns its argument needs a type - const saving = Substitute.for() - saving.save(Arg.all()).mimicks(async (entity: any) => entity) - saving.save(Arg.all()).mimicks(entity => Promise.resolve(entity as any)) - saving.save({ id: 2 }).then(saved => console.log(saved)) // prints { id: 2 } - // @ts-expect-error entity is a DeepPartial[] | DeepPartial, and so is what the function returns - saving.save(Arg.all()).mimicks(async entity => entity) - ``` - - ```typescript - import { Substitute, Arg, configure, received } from '@fluffy-spoon/substitute' - - // the shapes of AWS SDK v3's S3Client.send(), in short: Command is invariant in its type parameters - interface GetObjectInput { Bucket: string; Key: string } - interface PutObjectInput { Bucket: string; Key: string; Body: string } - interface GetObjectOutput { Body?: string } - interface PutObjectOutput { ETag?: string } - type ServiceInputTypes = GetObjectInput | PutObjectInput - type ServiceOutputTypes = GetObjectOutput | PutObjectOutput - class Command { - constructor(readonly input: Input) {} - // the middleware takes and returns the command's types - middleware: Array<(input: Input, output: Output) => Output> = [] - } - class GetObjectCommand extends Command {} - class PutObjectCommand extends Command {} - interface S3Client { - send(command: Command): Promise - send(command: Command, cb: (err: unknown, data?: Output) => void): void - } - const object: GetObjectOutput = { Body: 'a,b' } - - const s3 = Substitute.for() - s3.send(Arg.any()).resolves(object) - s3.send(Arg.all()).resolves(object) - s3.send(Arg.is(command => command instanceof GetObjectCommand && command.input.Key === 'report.csv')).resolves(object) - s3[configure]().send(Arg.is(command => command instanceof GetObjectCommand)).resolves(object) - // the code under test - s3.send(new GetObjectCommand({ Bucket: 'b', Key: 'report.csv' })).then(result => console.log(result.Body)) // prints a,b - // checks take every form - s3.received(1).send(Arg.is((command: GetObjectCommand) => command.input.Key === 'report.csv')) - s3[received](0).send(new PutObjectCommand({ Bucket: 'b', Key: 'report.csv', Body: '' })) - - const typed = Substitute.for() - // @ts-expect-error a concrete command gets the client's own overload, which has no setup API - typed.send(new GetObjectCommand({ Bucket: 'b', Key: 'report.csv' })).resolves(object) - // @ts-expect-error so does a typed predicate - typed.send(Arg.is((command: GetObjectCommand) => command.input.Key === 'report.csv')).resolves(object) - // @ts-expect-error and a cast - typed.send(Arg.any() as GetObjectCommand).resolves(object) - // @ts-expect-error a type guard does not fit the parameter's type - typed.send(Arg.is((command): command is GetObjectCommand => command instanceof GetObjectCommand)).resolves(object) - // @ts-expect-error in the configure view, a typed predicate fits no overload - typed[configure]().send(Arg.is((command: GetObjectCommand) => true)).resolves(object) - // @ts-expect-error no overload resolves to a string - typed.send(Arg.all()).resolves('x') - // plain TypeScript does not assign a GetObjectCommand to the Command of the constraints either - // @ts-expect-error - const erased: Command = new GetObjectCommand({ Bucket: 'b', Key: 'k' }) - ``` -* **Declaration emit** (`declaration: true`, or `composite: true`): a file can export a substitute, a check view (`export const view = pet.received()`, `pet[received]().speak`) and a function that returns one of them, but not the value of a member or a call of a substitute (`export const total = calc.total`, `export const sum = calc.add(1, 2)`), nor the `configure` view (`export const c = calc[configure]()`). For those, TypeScript reports TS4023, `Exported variable 'sum' has or is using name 'returns' from external module "…/dist/shared/Constants" but cannot be named` (also for `throws` and `mimicks`), because their setup methods are keyed by the library's symbols, which it cannot name in a declaration file. 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 (`export function makeCalc() { const calc = Substitute.for(); calc.total.returns(5); return calc }`). 2.0.0-beta.4 emitted declarations for these values. - - Check views of types with members keyed by symbols can be exported, too: iterables (`[Symbol.iterator]`), async iterables, `Map`, `Set`, objects with a `[Symbol.toStringTag]`, and Node.js' `EventEmitter` and everything built on it, such as streams and `http.Server`. On TypeScript 4.5 and newer, the declaration file refers to such a view by the exported type `CheckViewOf`, as `import("@fluffy-spoon/substitute").CheckViewOf` (or `CheckViewOf` when the file imports it), with every `moduleResolution`, which projects with `node10`, `node16`, `nodenext` and `bundler` resolution read; TypeScript 3.6 and 4.1 write such a view out in full. For a member of a check view (`export const addView = bag.received().add`, `bag[received](1).add`) and for an exported matcher (`export const positive = Arg.is((x: number) => x > 0)`, `export const all = Arg.all()`), TypeScript 5.9 and older with `moduleResolution: node` write the directory path `import("@fluffy-spoon/substitute/dist/shared")` into the declaration file. The package's `exports` map that directory to its index (and `dist/api` and `dist/api/types`, the other directories that its own declarations import), so projects with `node16`, `nodenext` (ES modules and CommonJS) or `bundler` resolution read such declaration files with full types. This is checked with TypeScript 5.0, 5.4, 5.9 and 7.0.2, without `skipLibCheck`. - - Generic helpers need a type annotation when the type that TypeScript infers for an export is a substitute of `T | undefined` or `T | null` (`function optional(sub: SubstituteOf) { return sub }`, or a field `sub = Substitute.for()`), or a member or check view of a substitute of a constrained type parameter (`function addView(sub: SubstituteOf) { return sub.received().add }`). Without one, declaration emit does not finish on TypeScript 3.6, runs out of memory on 4.5 (`JavaScript heap out of memory`, without a diagnostic); 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. Annotate the type, which emits on every version from 3.6 on: `SubstituteOf` for the first ones (also for a field), `CheckViewOf` for a check view, and the types of the constraint for a member of a constrained type parameter, as below. A member annotated with the type parameter itself (`SubstituteOf['add']`) does not compile. - - A helper that returns a check view is annotated with `CheckViewOf`, the type that `received()`, `didNotReceive()`, `[received]()` and `[didNotReceive]()` return: `function once(sub: SubstituteOf): CheckViewOf { return sub[received](1) }` compiles for the string and the symbol forms, with an unconstrained type parameter, a constrained one (`T extends Calculator`) and `T | undefined` (`CheckViewOf`), and a member of a check view is `CheckViewOf['add']`. Such annotations are what `isolatedDeclarations` (TypeScript 5.5 and newer) and JSR's "no slow types" ask for, and these helpers emit with it, and are read with `node10`, `node16`, `nodenext` and `bundler` resolution. The forms written with the type parameter do not compile in generic code (TS2322): `ReturnType['received']>`, `ReturnType['didNotReceive']>` and `ReturnType[typeof received]>`, while `ReturnType` does for the string forms. - - ```typescript - import { Substitute, SubstituteOf, CheckViewOf, Arg, received, didNotReceive } from '@fluffy-spoon/substitute' - - export interface Calculator { add(a: number, b: number): number; total: number } - - export function optional(sub: SubstituteOf): SubstituteOf { return sub } - export class OptionalFixture { sub: SubstituteOf = Substitute.for() } - - export function once(sub: SubstituteOf): CheckViewOf { return sub.received(1) } - export function onceSymbol(sub: SubstituteOf): CheckViewOf { return sub[received](1) } - export function never(sub: SubstituteOf): CheckViewOf { return sub[didNotReceive]() } - export function optionalView(sub: SubstituteOf): CheckViewOf { return sub[received](1) } - - export function member(sub: SubstituteOf): SubstituteOf['add'] { return sub.add } - export function viewMember(sub: SubstituteOf): CheckViewOf['add'] { return sub.received().add } - export function view(sub: SubstituteOf): CheckViewOf { return sub.received() } - export function whole(sub: SubstituteOf): SubstituteOf { return sub } - - const calculator = Substitute.for() - member(calculator)(1, 2).returns(3) - console.log(calculator.add(1, 2)) // prints 3 - once(calculator).add(1, 2) - onceSymbol(calculator).add(1, Arg.any()) - never(calculator).add(3, 4) - view(calculator).add(1, 2) - viewMember(calculator)(1, 2) - ``` -* **Methods with a parameter declared with a literal type** (`once(event: 'drain', listener: () => void)`, `get(kind: 'user', id: number)`, also with a number or boolean literal, and with `null` from TypeScript 4.0 on), overloaded or not, resolve to the interface's own declaration when you call them directly with arguments that fit that declaration, so they have no setup API there: TypeScript tries such signatures before all others. `Arg.any()` fits any parameter, so it fits there, too. Configure them through the `configure` view: `stream[configure]().once('drain', Arg.any()).returns(stream)`. Checks work as usual (`stream.received(1).once('drain', Arg.any())`). A type matcher fits no literal type (see [Matching by type](#matching-by-type)), so where another overload takes any string, as `on(event: string, ...)` in Node.js' streams, `stream.on(Arg.any('string'), Arg.any()).returns(stream)` takes that overload and has the setup API. Parameters typed with a union of literals (`mode: 'r' | 'w'`) or with an enum member are not affected: `file.open('r').returns(1)` compiles (a type matcher does not fit them, either). -* **Overloaded generic methods whose parameter types depend on a type parameter through a conditional type**, such as `@types/pg`'s `Pool.query` and `ClientBase.query` (`values?: QueryConfigValues`, with `QueryConfigValues = T extends Array ? T : never`): a setup that passes values has no setup API, as in `pool.query(sql, [1]).resolves(result)`, also with `values` in a config object, with `Arg.any()` for the values, and in the `configure` view. The substitute sees each overload with its type parameters replaced by their constraints, which leaves `values` taking nothing, and checking the values against the method's own overloads cannot help, as TypeScript relates overloads with `any` for their type parameters and would accept any values. Calls without values (`pool.query('SELECT 1').resolves(result)`, `pool.query({ text })`), a setup with `Arg.all()` alone (`pool.query(Arg.all()).resolves(result)`, see [Ignoring all arguments](#ignoring-all-arguments)) and checks (`pool.received(1).query(sql, [1])`) compile. Pass the values `as never`: `pool.query(sql, [1] as never).resolves(result)`, `pool.query({ text: sql, values: [1] as never })`, and the same in `pool[configure]()`. That is the same call at runtime, so the setup answers the call that the code under test makes. Or match the SQL with any values: `pool.query(sql, Arg.all()).resolves(result)`. -* **More than 8 overloads:** only the last 8 have the setup API, in setups and in the `configure` view, and a setup with `Arg.all()` alone takes what one of these 8 returns. With `@types/node` 18 to 24, Node.js' `http.Server` declares 12 overloads of `on()` and of `once()`, in this order: one for any event name, then `'close'`, `'connection'`, `'error'`, `'listening'`, `'checkContinue'`, `'checkExpectation'`, `'clientError'`, `'connect'`, `'dropRequest'`, `'request'` and `'upgrade'`. So `server.on(Arg.any('string'), Arg.any()).returns(server)` does not compile, also not in the `configure` view, and the setup of one event, `server[configure]().on('request', Arg.any()).returns(server)`, compiles only for the events of the last 8 overloads: not for `'close'`, `'connection'` and `'error'`, also not with `once()`. `net.Socket` has the same limit for `'close'`, and with `@types/node` 22 and 24 also for `'connect'`, `'connectionAttempt'` and `'connectionAttemptFailed'`. A setup that compiles for every event is one with `Arg.all()`: `server[configure]().on(Arg.all()).returns(server)` makes `on()` return the server for every event, so that the code under test can chain it (`server.on('error', onError).on('close', onClose)`), and the same works with `once()` and for `net.Socket`. To get the listener of one event, give that setup a `mimicks()` that looks at the event name (see the example below). Checks work with every overload (`server.received(1).on('error', Arg.any())`, `server.received(1).on(Arg.any('string'), Arg.any())`). On the substitute itself, outside the `configure` view, the setup of one event (`server.on('request', Arg.any()).returns(server)`) has no setup API either, because its parameter has a literal type (see above). With `@types/node` 25 and newer, `http.Server` and `net.Socket` declare `on()` and `once()` as one generic method for their events and one for any other name, and every one of these setups compiles. -* **A last overload that no argument fits** once its type parameters are replaced by their constraints is left out of the setup API, the `configure` view and the `Arg.all()` setup. hono 4's `Context.get` and `Context.set` end with such an overload, `(key: Key): ContextVariableMap[Key]`, when the app adds nothing to `ContextVariableMap` (then `{}`, so that `Key` can only be `never`). So `c.get('user').returns(user)`, `c[configure]().get('user').returns(user)`, `c.get(Arg.all()).returns(user)` and the checks compile for `Substitute.for>()` (checked with hono 4.13; on TypeScript older than 5.7, hono's own types need `skipLibCheck`). The overloads that remain are typed as other generic methods, with their type parameters replaced by their constraints: `c.get('user')` is typed with the values of all the variables, so `.returns()` takes the value of any of them, and `const user: User = c.get('user')` written against the substitute does not compile. Read through the `Context` type there, as the code under test does (`const context: Context = c`). Keys that are not variables, and values that no variable holds, are still rejected (`c.get('nope')`, `c[configure]().get('user').returns(42)`). Only a last overload that returns `never` once its type parameters are replaced is left out this way. When such an overload comes before others, as `find(key: K, extra: {}[K]): {}[K]` does between `find(id: number): string` and `find(name: string, exact: boolean): number`, the method is typed by its last overload alone, as a generic method. Its setups, its `configure` view and its checks then take the last overload's arguments, and also any other arguments of that number, because the impossible overload takes every argument: `finder.find(1, 2).returns(1)` and `finder.received(1).find('ann', 'not a boolean')` compile, although TypeScript rejects these calls on `Finder`. `.returns()` and a single `Arg.all()` take what the last overload returns, and a call with another number of arguments is typed by the method's own overloads, without the setup API (`finder.find(2).returns('b')` does not compile). The number is the last overload's, not the impossible overload's. When the impossible overload takes more parameters than the last one, calls with other numbers of arguments do not compile under `strict`, and a call with the last overload's number of arguments that only an earlier overload takes is typed `any` (for `find(id: number): string`, `find(key: K, a: {}[K], b: {}[K]): {}[K]` and `find(name: string): number`, `f.find(1).returns('anything')` compiles). An impossible overload that returns another type (`get(key: K): string`) is kept, wherever it is: it takes no argument, so calls that no other overload takes do not compile in setups, checks and the `configure` view, but a single `Arg.all()` takes its return type as well. Cast to a type with the overload that you need: `(finder as unknown as SubstituteOf<{ find(id: number): string }>).find(1).returns('a')`. - - ```typescript - import { Substitute, Arg, configure, SubstituteOf } from '@fluffy-spoon/substitute' - - // the shapes of hono 4's Context, in short: ContextVariableMap is {} until the app adds to it - interface ContextVariableMap {} - type Variables = { user: { id: string }; requestId: string } - interface Get { - (key: Key): Variables[Key] - (key: Key): ContextVariableMap[Key] - } - interface Context { get: Get } - - const c = Substitute.for() - c.get('user').returns({ id: 'u1' }) - c[configure]().get('requestId').returns('r1') - c.get(Arg.all()).returns({ id: 'anyone' }) - - // the code under test reads through the Context type - const context: Context = c - const user: { id: string } = context.get('user') - console.log(user.id, context.get('requestId')) // prints u1 r1 - c.received(1).get('user') - // @ts-expect-error not a variable - c.didNotReceive().get('nope') - // @ts-expect-error no variable holds a number - c[configure]().get('user').returns(42) +You need Node.js 10 or newer (12.17+ for `import`) and, if you use TypeScript, TypeScript 3.6 or newer. Still on version 1? Pin it with `@fluffy-spoon/substitute@1` and see the [migration guide](MIGRATION.md) for upgrading. - interface Finder { - find(id: number): string - find(key: K, extra: {}[K]): {}[K] - find(name: string, exact: boolean): number - } - const finder = Substitute.for() - finder.find('ann', true).returns(1) - // the impossible overload in the middle: two arguments of any type compile, also in checks - finder.find(1, 2).returns(1) - finder.didNotReceive().find('ann', 'not a boolean') - // @ts-expect-error one argument: the method's own first overload, without the setup API - finder.find(2).returns('b') - // @ts-expect-error .returns() takes what the last overload returns - finder.find(3, 4).returns('a') - ;(finder as unknown as SubstituteOf<{ find(id: number): string }>).find(1).returns('a') - console.log(finder.find(1), finder.find('ann', true)) // prints a 1 - - // an impossible overload that returns another type is kept: it takes no argument, but a single Arg.all() takes its type - interface Getter { - get(key: K): Variables[K] - get(key: K): string - } - const getter = Substitute.for() - getter.get('requestId').returns('r1') - getter.get(Arg.all()).returns('any string') - // @ts-expect-error not a variable - getter.get('nope') - // @ts-expect-error not in checks either - getter.received(1).get('nope') - console.log(getter.get('requestId'), getter.get('user')) // prints r1 any string - ``` -* **A property typed `never`** cannot be configured. On a method that returns `never`, `.returns()` only accepts `never`; use `.throws()`. -* **Members typed only `null` or `undefined`** (`error?: undefined`, `ownerDocument: null`) keep their plain type and have no setup API. Configure them through `sub[configure]()`. -* **Generic code:** the result of a call on the substitute (`box.get('a')`) is not assignable to `T`; read it through the plain interface type, or cast it. Checking a set of a property whose type is the type parameter itself (`holder.received().current = value`, with `current: T`) may not compile; write `(holder.received() as Holder).current = value`. Setups of such a property (`box.current.returns(value)`, and from TypeScript 3.9 on also with `maybe?: T` or `orNull: T | null`), of properties of types like `T[]` or `Promise`, and of calls that return `T` are fine. With a constrained type parameter, a promise-typed property of the constraint (`name: Promise` in `Repo`, with `T extends Repo`) has no `.resolves()` or `.rejects()` (nor `[resolves]` and `[rejects]`, also not in the `configure` view), while promise-returning methods have them: write `repo.name.returns(Promise.resolve('ann'))`, or `.returns(Promise.reject(error))`, which work on every supported version. Concrete types are not affected. -* **Generic code on TypeScript older than 4.8:** on TypeScript 3.6 to 4.7, with a constrained type parameter (``), calls of optional methods and of members typed as a function or `undefined` have no setup API: `sub.reset().returns()` with `reset?(): void`, `sub.find('a').returns('b')` with `find?(id: string): string | undefined`, `sub.maybeAdd(1).returns(2)` with `maybeAdd: ((a: number) => number) | undefined`, and every method of `T extends Partial` (TypeScript reports "This expression is not callable"). On TypeScript 3.6 to 3.8, in addition, properties whose type includes `null` or `undefined` have no setup API: with a constrained type parameter (`name: string | null`, `limit?: number`, every property of `T extends Partial`), and also in an interface instantiated with any type parameter, constrained or not (`maybe?: T` and `orNull: T | null` in `SubstituteOf>`). Configure them through the `configure` view, which works on every version: `sub[configure]().reset().returns()`, `sub[configure]().limit.returns(10)`, `box[configure]().maybe.returns(value)`. Checks work as well (`sub.received().reset()`, `sub.received().name = null`). Calls of optional methods in an instantiated interface (`load?(): T` in `Box`) work on every version. TypeScript 4.8 and newer have none of these limitations. -* **Generic code with a union constraint** whose variants' methods return different types: in `function stubPet(pet: SubstituteOf)`, where `speak()` returns `'meow'` or `'woof'`, `.returns()` and the `configure` view take `never` (`pet.speak().returns('meow')` does not compile). Members whose signature is the same in every variant (`pet.age().returns(3)`) and properties (`pet.kind.returns('cat')`) work. Cast to the constraint: `(pet as SubstituteOf).speak().returns('meow')`. On TypeScript 5.4 and newer, a method that the variants of a union constraint declare with different parameter lists has no setup API at all, even when every variant returns the same type: with `log(message: string): void` in `LogA` and `log(message: string, level?: number): void` in `LogB`, `sub.log('x').returns()` does not compile in `function stubLog(sub: SubstituteOf)` (TypeScript 5.0 and older compile it). The `configure` view (`sub[configure]().log('x').returns()`), checks (`sub.received().log('x')`) and the cast to the constraint work there on every version. A concrete union, as in `Substitute.for()`, takes the union of the return types: `pet.speak().returns('meow')` compiles there, and so does `pet.speak().returns('woof')`, also when the variants have a string index signature, and when they declare the method with different parameter lists (see the next item). -* **A method that the variants of a concrete union declare with different parameter lists** (an extra optional parameter, other parameter types or other overloads, such as `read(path): string` and `read(path, encoding?): Uint8Array` in `Substitute.for()`) has the setup API, and `.returns()` takes the return types of the variants that the call can reach. Each call is checked against the parameter list of one variant as a whole, in setups, checks and the `configure` view, so arguments that no variant accepts together do not compile, also when every variant returns the same type: with `move(x: string, y: number): void` in one variant and `move(x: number, y: string): void` in the other, `shape.move('a', 'b')` does not compile. A callback without parameter types gets them from the parameter list that the call resolves to, also in large unions such as the union of all HTML element types (`anyElement.addEventListener('click', event => event.preventDefault())`). A callback that annotates `this` with the type of a variant whose method takes it compiles: with `onClick(listener: (this: Button, x: number) => void)` in `Button` and `(this: Link, x: number) => void` in `Link`, both `function (this: Button, x: number) { }` and `function (this: Link, x: number) { }` do. Such a call takes that variant's return type, on every TypeScript version from 3.6 on, also when it leaves out an optional parameter: with `onPress(listener: (this: Btn, x: number) => void, options?: { once: boolean }): 'b'` in `Btn` and the same with `Lnk` and `'l'`, `widget.onPress(function (this: Btn, x: number) { }).returns('b')` compiles, and `.returns(true)` does not. Callbacks with the `this` types of different variants in one call (`both(function (this: C1) { }, function (this: C2) { })`) do not compile, in setups, checks and the `configure` view, as TypeScript rejects that call on the union itself. A callback with a `this` that no variant takes does not compile either, and a callback without a `this` annotation gets the `this` types of all variants. Which variants a call can reach depends on the number of arguments that it passes. A call that leaves out an optional parameter in which the variants differ takes what every variant that accepts the call returns: with `get(key: string, options?: OptionsV1): number` in one variant and `get(key: string, options?: OptionsV2): string` in the other, `api.get('k').returns(1)` and `api.get('k').returns('s')` both compile, while `api.get('k', { retries: 1 }).returns('s')`, with `OptionsV1` options, does not. A single `Arg.all()` takes the return types of every variant, and a variant with a rest parameter counts for calls with any number of arguments. On TypeScript 3.6 to 5.3, `Arg.all()` after other arguments takes `never` when the variants' parameter lists have different lengths: with `on(cb)` in one variant and `on(cb, extra: number)` in the other, `ab.on(x => { }, Arg.all()).returns('rb')` does not compile there (it does on 5.4 and newer). Use `Arg.all()` alone, or cast to the variant. If every overload of every variant returns the same type, or one of them returns `any`, `.returns()` takes that type. Three cases can surprise: - * The values of the arguments do not count, so parameter types that only overlap do not either: with `letter(x: 'a' | 'b'): 'lower'` in one variant and `letter(x: 'b' | 'c'): 'upper'` in the other, `letters.letter('b').returns('upper')` does not compile. - * `Arg.any()`, and an `Arg.is()` predicate without a parameter type, resolve to the first variant's overload that takes that many arguments. When the variants' parameter types differ, such a call takes only the return types of the variants that accept that overload's parameters: with `m(x: string): 'A'` in `MatchA` and `m(x: number): 'B'` in `MatchB`, `matched.m(Arg.any()).returns('B')` does not compile. Use `Arg.all()`, or a typed matcher such as `Arg.any('number')`. - * A call that resolves to an overload with optional parameters also counts the variants whose parameter lists overlap with that overload's whole list: with `read(path): string` and `read(path, encoding?): Uint8Array`, `reader.read('p', 'utf8').returns('text')` compiles, although only the second variant takes an encoding. +## Quick start - In these cases, cast to the variant: `(letters as SubstituteOf).letter('b').returns('upper')`. Editors and error messages show the parameters of such a method without their names (`AllArguments<[string, (string | undefined)?]>`). -* **Checking a set of an index-signature key in generic code:** with `T extends Settings`, where `Settings` is `{ [key: string]: number; port: number }`, keys that exist only through the index signature can be configured (`sub.timeout.returns(5)`) and read in a check (`sub.received().timeout`). A check of a set, `sub.received().timeout = 5` (also with `[received]()`, `didNotReceive()` or `received(1)`), does not compile, because TypeScript does not resolve a write through an index signature of a type parameter. Write `(sub.received() as Settings).timeout = 5`, or `(sub as SubstituteOf).received().timeout = 5`. -* **A union with `null` or `undefined`** (`Substitute.for()`) has no setup API. Substitute `Calculator`: the substitute can be passed where a `Calculator | undefined` is expected. -* **`Arg.all()` after other arguments** type-checks after up to 6 of them, also after a callback that annotates `this` with the type of a variant of a concrete union (with `onClick(listener: (this: Btn, n: number) => void, options?: { once: boolean }): 'b'` in `Btn`, `widget.onClick(function (this: Btn, n: number) { }, Arg.all()).returns('b')` takes `Btn`'s return type), and after the leading arguments of `emit()` on Node.js' `EventEmitter` (see the generic methods above). It does not type-check with arguments after it (which is an error at runtime, too), after the last parameter of a fixed parameter list (`add(1, 2, Arg.all())`; `EventEmitter.emit` does not check the number of an event's arguments, see above), or inside an object or array. Editors show the signatures that accept it with parameters named `arg0`, `arg1`, and so on. -* **A lone `Arg.any()`** compiles for a method with more parameters (`calculator.add(Arg.any())`), because it also fits the signature that takes `Arg.all()`, but it only matches calls with one argument; see [Ignoring all arguments](#ignoring-all-arguments). -* **`.resolves()` and `.rejects()`** are offered only where a native promise of the value fits the member's type, so not for a thenable with members of its own, such as a query builder, nor for a subtype of `Promise` with members of its own, such as ky's `ResponsePromise`, knex's `QueryBuilder`, execa's result or a `CancellablePromise`; see [Working with promises](#working-with-promises). -* **`Arg.any('object')`** is typed `any`, like `Arg.any()`, so the compiler does not check it against the parameter. `Arg.any('function')` is typed as any function or class. -* **`Arg.any.not(type)`** is typed as that type, so `Arg.any.not('number')` only fits a parameter that accepts every number, although it matches every value that is not a number. Like `Arg.any('number')`, it does not fit a union of number literals such as `80 | 443`, and `Arg.any.not('string')` does not fit `'EUR' | 'USD'`. On a parameter that does not accept numbers it would match every value, so use `Arg.any()` there. `Arg.any.not('undefined')` fits any parameter. -* **An optional function-typed property** (`onChange?: (value: string) => void`) does not accept `undefined` in a check: `widget.received().onChange = undefined` does not compile, nor do the `[received]()`, `didNotReceive()` and `[didNotReceive]()` forms, because in a check the member is callable (`widget.received().onChange('x')` checks a call). Write `(widget.received() as Widget).onChange = undefined`, or `widget.received().onChange = Arg.any.not('function')`, which matches any value that is not a function. (`Arg.any('undefined')` does not fit there either.) -* **Assigning a function to a callable member in a check** (`button.received().onClick = handler`) does not compile, because in a check the member also has the call signatures that take `Arg.all()`. Write `(button.received() as Button).onClick = handler`. Matchers fit there, `Arg.any('function')` included (`button.received().onClick = Arg.any('function')`), also on a union. On a substitute of a union, a function or constructor assigned to such a member in a check must fit both those call signatures and the member's type as TypeScript writes it on the union, so a function without parameters, or whose parameters take any value, compiles there as it would on the plain union: with `fmt(v: number): string` in `Cat` and `fmt(v: number): number` in `Dog`, `pet.received().fmt = String` compiles, and so do `pet.received().onEvent = () => 1` for `onEvent: (e: string) => void` in both, and `els.received().addEventListener = () => {}` on `HTMLInputElement | HTMLSelectElement`. Where the member returns literal types that differ between the variants (`speak(loud: boolean): 'meow'` in `Cat`, `'woof'` in `Dog`), TypeScript infers the result of an arrow function there as a `string`, so `pet.received().speak = () => 'meow'` does not compile, also with `[received]()`, `didNotReceive()`, `[didNotReceive]()` and `received(1)`; `() => 'meow' as const` does, and so does a function declared to return `'meow'` that has no parameters or only parameters that take any value (`(): 'meow' => 'meow'`, `(loud: unknown): 'meow' => 'meow'`), by the rule above; one with the member's own parameters (`(loud: boolean): 'meow' => 'meow'`) does not. `String`, `Date` and classes do not fit `speak` either. Cast to the variant for any other function: `(pet.received() as Cat).speak = handler`. Matchers fit (`pet.received().speak = Arg.any('function')`, in each of these forms). Nor can `null` be assigned in a check to such a member that includes `null`: with `handler: ((e: MouseEvent) => void) | null` in one variant and `((e: KeyboardEvent) => void) | null` in the other, `widget.received().handler = null` does not compile; cast as above, or check with `Arg.is(handler => handler === null)`. -* **Optional properties of a type with a string index signature** do not accept `undefined` in a check (`sub.received().note = undefined`). Without an index signature, optional properties that are not functions do. -* **Nested auto-substitutes** are not typed as substitutes, see [Auto-substitutes](#auto-substitutes-and-nested-members). The result of a call is typed as the member's value with the setup API, without the check views, so a [check through a call with matchers](#through-a-call-with-matchers) needs a cast through `unknown`: `(app.repo(Arg.any()) as unknown as SubstituteOf).received(1).save(1)`, also after a setup that returns a substitute of your own. Without the cast, the string forms give TS2339 ("Property 'received' does not exist on type ...") and the symbol forms TS7053; a cast without `unknown` gives TS2352. +Say you want to test a service that depends on a repository and a logger: - + ```typescript -import { configure, SubstituteOf } from '@fluffy-spoon/substitute' - -// @ts-expect-error the property's type carries the setup API -calculator.isEnabled = true -const asCalculator: Calculator = calculator -asCalculator.isEnabled = true -// at runtime, both assignments are recorded -calculator.received(2).isEnabled = true - -interface Repository { - find(id: number): string | null -} -const repository = Substitute.for() -repository.find(1).returns(null) -const found: string | null = repository.find(1) -console.log(found) // prints null - -interface Store { - get(key: string): T -} -const store = Substitute.for() -store.get('answer').returns(42) -console.log(store.get('answer')) // prints 42 - -interface Socket { - on(event: 'data', listener: (data: string) => void): Socket - on(event: 'close', listener: () => void): Socket -} -const socket = Substitute.for() -socket[configure]().on('data', Arg.any()).returns(socket) -console.log(socket.on('data', () => { }) === socket) // prints true - -interface Stream { - once(event: 'drain', listener: () => void): Stream -} -const stream = Substitute.for() -// @ts-expect-error a parameter with a literal type: the call resolves to Stream's own declaration -stream.once('drain', Arg.any()).returns(stream) -stream[configure]().once('drain', Arg.any()).returns(stream) -stream.received(0).once('drain', Arg.any()) - -interface Readable { - on(event: 'close', listener: () => void): Readable - on(event: string, listener: (...args: any[]) => void): Readable -} -const readable = Substitute.for() -// a type matcher does not fit 'close', so the call takes the overload for any string -readable.on(Arg.any('string'), Arg.any()).returns(readable) -// @ts-expect-error Arg.any() fits 'close', so the call resolves to Readable's own declaration -readable.on(Arg.any(), Arg.any()).returns(readable) +import { Substitute, Arg } from '@fluffy-spoon/substitute' -interface File { open(mode: 'r' | 'w'): number } -const file = Substitute.for() -file.open('r').returns(1) +interface User { id: number; name: string } -interface Box { - current: T - items: T[] - get(key: string): T -} -function stubBox(box: SubstituteOf>, value: T) { - box.get(Arg.any()).returns(value) - box.items.returns([value]) - box.current.returns(value) +interface UserRepository { + find(id: number): Promise + save(user: User): Promise } -function checkCurrentSet(box: SubstituteOf>, value: T) { - (box.received() as Box).current = value -} -const box = Substitute.for>() -stubBox(box, 7) -console.log(box.current) // prints 7 -const replace = (b: Box) => { b.current = 8 } -replace(box) -checkCurrentSet(box, 8) -``` - -```typescript -interface Widget { - onChange?: (value: string) => void - onClick?: (event: string) => void +interface Logger { + warn(message: string): void } -const widget = Substitute.for() -const handler = (event: string) => { } // the code under test -const rewire = (w: Widget) => { - w.onChange = undefined - w.onClick = handler -} -rewire(widget) - -// @ts-expect-error an optional function-typed property does not accept undefined in a check -widget.received().onChange = undefined -;(widget.received() as Widget).onChange = undefined -widget.received().onChange = Arg.any.not('function') - -// @ts-expect-error in a check, a callable member also has the call signatures that take Arg.all() -widget.received().onClick = handler -;(widget.received() as Widget).onClick = handler -widget.received().onClick = Arg.any('function') +class UserService { + constructor(private readonly users: UserRepository, private readonly logger: Logger) { } -interface Greeter { - greet(name: string): string -} -const greeter = Substitute.for() -// @ts-expect-error Arg.any.not('number') is typed number -greeter.greet(Arg.any.not('number')).returns('hi') -greeter.greet(Arg.any()).returns('hi') -greeter.greet(Arg.any.not('undefined')).returns('hi') -interface Server { - listen(port: 80 | 443): void + async rename(id: number, name: string) { + const user = await this.users.find(id) + if (!user) { + this.logger.warn(`user ${id} not found`) + return false + } + await this.users.save({ ...user, name }) + return true + } } -const server = Substitute.for() -// @ts-expect-error Arg.any('number') is typed number, which is not 80 | 443 -server.listen(Arg.any('number')).returns() -server.listen(Arg.any('number') as 80 | 443).returns() -server.listen(Arg.is((port: 80 | 443) => true)).returns() -// @ts-expect-error Arg.any.not('number') is typed number, too -server.listen(Arg.any.not('number')).returns() -interface Cat { kind: 'cat'; speak(loud: boolean): 'meow' } -interface Dog { kind: 'dog'; speak(loud: boolean): 'woof' } -const meow = (loud: boolean): 'meow' => 'meow' -// the code under test -const teach = (pet: Cat | Dog) => { if (pet.kind === 'cat') pet.speak = meow } -const pet = Substitute.for() -pet.kind.returns('cat') -teach(pet) -// @ts-expect-error in a check, a function with the member's own parameters cannot be assigned to a member that the variants declare differently -pet.received().speak = meow -// @ts-expect-error nor a constructor -pet.didNotReceive().speak = String -// @ts-expect-error nor an arrow function whose result TypeScript infers as a string -pet.didNotReceive().speak = () => 'meow' -// a function that returns 'meow' and has no parameters, or only parameters that take any value, fits -pet.didNotReceive().speak = (): 'meow' => 'meow' -pet.didNotReceive().speak = (loud: unknown): 'meow' => 'meow' -pet.didNotReceive().speak = () => 'meow' as const -;(pet.received() as unknown as Cat).speak = meow -pet.received().speak = Arg.any('function') +// 1. create substitutes +const users = Substitute.for() +const logger = Substitute.for() -interface Clicks { kind: 'clicks'; handler: ((event: MouseEvent) => void) | null } -interface Keys { kind: 'keys'; handler: ((event: KeyboardEvent) => void) | null } -const input = Substitute.for() -// @ts-expect-error nor null, for such a member -input.received(0).handler = null -input.received(0).handler = Arg.is(handler => handler === null) +// 2. configure what they answer +users.find(1).resolves({ id: 1, name: 'ann' }) +users.find(Arg.is(id => id > 100)).resolves(undefined) -const maybeCalculator = Substitute.for() -// @ts-expect-error a union with undefined has no setup API -maybeCalculator.add(1, 2).returns(3) +const service = new UserService(users, logger) ``` -```typescript -import { Substitute, SubstituteOf, Arg, configure } from '@fluffy-spoon/substitute' - -interface Cat { kind: 'cat'; speak(): 'meow'; age(): number; load(): Promise } -interface Dog { kind: 'dog'; speak(): 'woof'; age(): number; load(): Promise } - -// a concrete union takes the union of the variants' return types -const pet = Substitute.for() -pet.speak().returns('woof') -pet.load().resolves('bone') -console.log(pet.speak()) // prints woof -// @ts-expect-error neither variant returns 'moo' -Substitute.for().speak().returns('moo') +Then run the code under test and check what it did: -function stubPet(pet: SubstituteOf) { - ;(pet as SubstituteOf).speak().returns('meow') - pet.age().returns(3) -} -function doesNotCompile(pet: SubstituteOf) { - // @ts-expect-error in generic code, .returns() only takes what every variant's speak() returns: never - pet.speak().returns('meow') -} -const genericPet = Substitute.for() -stubPet(genericPet) -console.log(genericPet.speak(), genericPet.age()) // prints meow 3 - -interface Settings { - [key: string]: number - port: number -} -function stubSettings(settings: SubstituteOf) { - settings.timeout.returns(5) - settings[configure]().retries.returns(3) -} -function checkTimeoutSet(settings: SubstituteOf) { - // @ts-expect-error a set of a key that exists only through the index signature cannot be checked here - settings.received().timeout = 10 - ;(settings.received() as Settings).timeout = 10 -} -const settings = Substitute.for() -stubSettings(settings) -console.log(settings.timeout + settings.retries) // prints 8 -const setTimeoutTo10 = (s: Settings) => { s.timeout = 10 } -setTimeoutTo10(settings) -checkTimeoutSet(settings) - -// a union constraint whose variants declare the method with different parameter lists -interface LogA { kind: 'a'; log(message: string): void } -interface LogB { kind: 'b'; log(message: string, level?: number): void } -function stubLog(log: SubstituteOf) { - // @ts-expect-error no setup API on TypeScript 5.4 and newer - log.log('x').throws(new Error('full')) - log[configure]().log('y').throws(new Error('full')) -} -const log = Substitute.for() -stubLog(log) -log.log('y') // throws Error: full - -// generic methods: the type parameters are replaced by their constraints -interface Config { port: number; host: string } -interface ConfigService { get(key: K): Config[K] } -const config = Substitute.for() -config.get('host').returns('localhost') -console.log(config.get('host')) // prints localhost -// Config[keyof Config] is number | string, so this compiles, too -config.get('port').returns('eighty') -// @ts-expect-error no member of Config is a symbol -config[configure]().get('port').returns(Symbol('80')) -// @ts-expect-error get() takes one argument -config.get('port', 'extra') -// a matcher for the key takes what get() returns for keyof Config -config.get(Arg.is(key => key === 'port')).returns(80) -// @ts-expect-error get() returns number | string -config.get(Arg.is(key => key === 'host')).returns(true) - -// arguments that fit only the constraints: the value is checked against what same() returns for them -interface Pairs { same(a: T, b: T): T } -const pairs = Substitute.for() -pairs.same(1, 'x').returns('y') -console.log(pairs.same(1, 'x')) // prints y -// @ts-expect-error same() returns string | number for these arguments -Substitute.for().same(1, 'x').returns({}) + +```typescript +async function test() { + // 3. exercise the code under test + console.log(await service.rename(1, 'anna')) // prints true + console.log(await service.rename(404, 'nobody')) // prints false -// a promise-typed property of a constraint: returns() a promise -interface Repo { name: Promise; load(): Promise } -function stubRepo(repo: SubstituteOf) { - repo.load().resolves(1) - repo.name.returns(Promise.resolve('ann')) + // 4. verify the calls it made + users.received(1).save({ id: 1, name: 'anna' }) + logger.received(1).warn('user 404 not found') + logger.didNotReceive().warn('user 1 not found') } -function doesNotCompileEither(repo: SubstituteOf) { - // @ts-expect-error no resolves() on a promise-typed property of the constraint - repo.name.resolves('ann') -} -const repo = Substitute.for() -stubRepo(repo) -repo.name.then(name => console.log(name)) // prints ann +test() +``` -interface Events { saved: (id: string) => void; failed: (error: Error) => void } -interface Emitter { emit(event: E, ...args: Parameters): boolean } -const emitter = Substitute.for() -emitter.emit('saved', 'id1').returns(true) -console.log(emitter.emit('saved', 'id1')) // prints true -emitter.received(1).emit('saved', 'id1') -// the event and its arguments are not matched up, so this compiles, too -emitter.didNotReceive().emit('failed', 'id1') -// a predicate in the event's arguments needs a parameter type -emitter.emit('saved', Arg.is((id: string) => id.startsWith('o'))).returns(true) -// @ts-expect-error without it, id gets the parameter types of all events: string | Error -emitter.emit('saved', Arg.is(id => id.startsWith('o'))).returns(true) +A failed check throws a `SubstituteException`, so it fails the test in whatever runner you use. -// a type parameter's default is not used: child() is taken as returning a Logger -type Logger = { info(message: string): void } - & { [level in Levels]: (message: string) => void } - & { child(bindings: object): Logger } -const logger = Substitute.for() -// @ts-expect-error a Logger is not a Logger -logger.child(Arg.any()).returns(Substitute.for()) -const childLogger = Substitute.for>() -logger.child(Arg.any()).returns(childLogger) -logger.child({ module: 'auth' }).info('started') -logger.received(1).child({ module: 'auth' }) +## Cheat sheet -// a return type that is conditional on the type parameter: .returns() takes any value -interface Converter { convert(value: T): T extends string ? number : boolean } -const converter = Substitute.for() -converter.convert('42').returns(42) -console.log(converter.convert('42')) // prints 42 -``` +The examples below use this interface: + ```typescript import { Substitute, Arg } from '@fluffy-spoon/substitute' -interface Job { data: D } -// the worker keeps its processor in a property, as bullmq's Worker does -interface Worker { processFn: (job: Job) => Promise; close(): Promise } -interface WorkerFactory { create(name: string, processor: (job: Job) => Promise): Worker } - -const factory = Substitute.for() -const worker = Substitute.for>() -// D is erased to unknown, and a Worker<{ userId: string }> is not a Worker: cast through unknown -factory.create('digest', Arg.any()).returns(worker as unknown as Worker) - -// the code under test -const started = factory.create<{ userId: string }>('digest', async job => { job.data.userId.trim() }) -console.log(started === worker) // prints true - -// @ts-expect-error a Worker<{ userId: string }> does not fit Worker -factory.create('digest', Arg.any()).returns(worker) - -// the same for a generic class used as a constructor substitute -class DigestWorker { - constructor(public name: string, public processFn: (job: Job) => Promise) { } - close() { return Promise.resolve() } +interface Calculator { + add(a: number, b: number): number + divide(a: number, b: number): number + heavyOperation(...numbers: number[]): Promise + isEnabled: boolean } -const DigestWorkerClass = Substitute.for() -const digestWorker = Substitute.for>() -DigestWorkerClass('digest', Arg.any()).returns(digestWorker as unknown as DigestWorker) -console.log(new DigestWorkerClass('digest', async () => { }) === digestWorker) // prints true -DigestWorkerClass.received(1)('digest', Arg.any()) -// @ts-expect-error neither does a DigestWorker<{ userId: string }> -DigestWorkerClass('digest', Arg.any()).returns(digestWorker) -``` - -```typescript -import { EventEmitter } from 'events' -import * as http from 'http' -import { Substitute, Arg, configure } from '@fluffy-spoon/substitute' - -type OrderEvents = { paid: [orderId: string, amount: number]; cancelled: [orderId: string] } -const orders = Substitute.for>() -orders.emit('paid', 'o1', 20).returns(true) -// the number of emit()'s arguments depends on the event, so this compiles, too -orders.emit('paid', 'o1').returns(true) -// a callback gets no parameter types from a generic method: annotate them -orders.on('paid', (orderId: string, amount: number) => { }).returns(orders) - -// Arg.all() after the leading arguments -orders.emit('paid', 'o2', Arg.all()).returns(false) -// a predicate in the event's arguments needs a parameter type -orders[configure]().emit('paid', Arg.is((orderId: string) => orderId.startsWith('x')), Arg.any()).returns(false) -// the code under test -console.log(orders.emit('paid', 'o1', 20), orders.emit('paid', 'o2', 5)) // prints true false -orders.received(2).emit('paid', Arg.all()) -orders.didNotReceive().emit('cancelled', Arg.all()) -orders.received(2).emit(Arg.any(), Arg.all()) - -// http.Server: on() for every event, and the listener of one event -const server = Substitute.for() -const listeners: { [event: string]: (...args: any[]) => void } = {} -server[configure]().on(Arg.all()).mimicks((event: string | symbol, listener: (...args: any[]) => void) => { - listeners[String(event)] = listener - return server -}) - -// the code under test -const failures: string[] = [] -server.on('error', (error: Error) => failures.push(error.message)).on('close', () => { }) - -listeners.error(new Error('EADDRINUSE')) -console.log(failures) // prints [ 'EADDRINUSE' ] -server.received(1).on('error', Arg.any()) -server.received(2).on(Arg.any('string'), Arg.any()) +const calculator = Substitute.for() ``` -What `@types/node` 18.19.63 to 24.x rejects (from `@types/node` 25 on, the lines marked `@ts-expect-error` compile): +### Return values - + ```typescript -import { EventEmitter } from 'events' -import * as http from 'http' -import { Substitute, Arg, configure } from '@fluffy-spoon/substitute' - -type OrderEvents = { paid: [orderId: string, amount: number]; cancelled: [orderId: string] } -const orders = Substitute.for>() -// the leading arguments are checked against emit()'s own signature -orders.emit('paid', 'o2', Arg.all()).returns(false) -// @ts-expect-error there is no event called 'refunded' -orders.emit('refunded', Arg.all()).returns(false) -// @ts-expect-error without a parameter type, orderId is unknown -orders.emit('paid', Arg.is(orderId => orderId.startsWith('x')), Arg.any()).returns(false) +calculator.add(1, 2).returns(3) // every add(1, 2) returns 3 +calculator.add(2, 2).returns(4, 5) // 4, then 5 from then on +calculator.isEnabled.returns(true) // properties work the same way +calculator.heavyOperation(1).resolves(42) // a resolved promise +calculator.heavyOperation(0).rejects(new Error('too light')) +calculator.divide(Arg.any(), 0).throws(new Error('cannot divide by 0')) +calculator.add(10, Arg.any()).mimicks((a, b) => a * b) // run your own implementation -// http.Server declares 12 overloads of on(), the one for any event name first -const server = Substitute.for() -// @ts-expect-error only the last 8 overloads have the setup API -server.on(Arg.any('string'), Arg.any()).returns(server) -server[configure]().on('request', Arg.any()).returns(server) -// @ts-expect-error 'error' is not among the last 8 overloads -server[configure]().on('error', Arg.any()).returns(server) -server[configure]().on(Arg.all()).returns(server) +console.log(calculator.add(1, 2)) // prints 3 +console.log(calculator.add(2, 2), calculator.add(2, 2), calculator.add(2, 2)) // prints 4 5 5 +console.log(calculator.isEnabled) // prints true +console.log(calculator.add(10, 5)) // prints 50 +calculator.divide(1, 0) // throws Error: cannot divide by 0 +calculator.heavyOperation(1).then(result => console.log(result)) // prints 42 ``` -```typescript -import { Substitute, Arg, configure } from '@fluffy-spoon/substitute' - -// the shape of @types/pg's Pool.query -type QueryConfigValues = T extends Array ? T : never -interface QueryConfig { text: string; values?: QueryConfigValues } -interface QueryResult { rows: R[] } -interface Pool { - query(config: QueryConfig): Promise> - query(text: string | QueryConfig, values?: QueryConfigValues): Promise> -} - -// the code under test -const findUser = (pool: Pool, id: number) => pool.query('SELECT * FROM users WHERE id = $1', [id]).then(result => result.rows[0]) - -const pool = Substitute.for() -// @ts-expect-error a setup that passes values has no setup API -pool.query('SELECT * FROM orders WHERE id = $1', [1]).resolves({ rows: [] }) -pool.query('SELECT * FROM users WHERE id = $1', [1] as never).resolves({ rows: [{ id: 1 }] }) -pool.query({ text: 'SELECT * FROM users WHERE id = $1', values: [2] as never }).resolves({ rows: [] }) -pool[configure]().query('SELECT * FROM users WHERE id = $1', [3] as never).resolves({ rows: [] }) -pool.query('SELECT now()', Arg.all()).resolves({ rows: [] }) -pool.query('SELECT 1').resolves({ rows: [] }) +### Argument matchers -findUser(pool, 1).then(user => console.log(user)) // prints { id: 1 } -pool.received(1).query('SELECT * FROM users WHERE id = $1', [1]) -``` +| Matcher | Matches | +|---|---| +| `Arg.any()` | any value, including `undefined` and `null` | +| `Arg.any('string')` | values of a type: `'string'`, `'number'`, `'boolean'`, `'object'`, `'array'`, `'function'`, ... | +| `Arg.is(x => x > 0)` | values for which the predicate is truthy (the parameter type is inferred) | +| `Arg.is.not(...)`, `Arg.any.not(...)` | the inverse of the matcher | +| `Arg.all()` | any number of remaining arguments, including none | +| `{ id: Arg.any(), name: 'bob' }` | matchers also work inside plain objects and arrays | +| `expect.any(String)`, `sinon.match(...)` | the asymmetric matchers of jest, vitest and sinon work too | + ```typescript -import { Substitute, SubstituteOf, Arg, configure } from '@fluffy-spoon/substitute' - -// each call is checked against one variant's parameter list as a whole -interface Left { side: 'left'; move(x: string, y: number): void } -interface Right { side: 'right'; move(x: number, y: string): void } -const shape = Substitute.for() -shape.move('a', 1).returns() -shape[configure]().move(1, 'b').returns() -// @ts-expect-error neither variant takes (string, string) -shape.received(0).move('a', 'b') - -// a callback without parameter types gets them from the variant's parameter list -interface SocketV1 { version: 1; onMessage(listener: (data: string) => void): void } -interface SocketV2 { version: 2; onMessage(listener: (data: Uint8Array) => void): void } -const socket = Substitute.for() -socket.onMessage(data => data.length).returns() +calculator.add(1, 2).returns(3) +calculator.add(Arg.is(a => a > 100), Arg.any('number')).returns(100) +calculator.add(Arg.all()).returns(0) -// a callback that annotates `this` with a variant's type -interface Button { kind: 'button'; onClick(listener: (this: Button, x: number) => void): void } -interface Link { kind: 'link'; onClick(listener: (this: Link, x: number) => void): void } -interface Image { kind: 'image' } -const control = Substitute.for