Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
200 commits
Select commit Hold shift + click to select a range
b2e6048
child_process: validate arguments for null bytes
RaisinTen Oct 14, 2022
824dcfc
src: return void in InitializeInspector()
joyeecheung Oct 14, 2022
c45b6ae
bootstrap: merge main thread and worker thread initializations
joyeecheung Oct 14, 2022
c3dd696
events: add unique events benchmark
anonrig Sep 15, 2022
8199841
lib: support more attributes for early hint link
anonrig Oct 14, 2022
edb92f4
doc: add anonrig to collaborators
anonrig Oct 14, 2022
c59d3b7
test: refactor promises to async/await
sonimadhuri Oct 14, 2022
ffba321
doc: add info on fixup to security release process
mhdawson Sep 27, 2022
a618dc3
test: use CHECK instead of EXPECT where necessary
tniessen Sep 26, 2022
f0c18f0
doc: fix undici version in changelog
mhdawson Oct 12, 2022
4825786
test: improve test coverage in `test-child-process-spawn-argv0.js`
juanarbol Oct 14, 2022
ea0cfc9
test: add test to improve coverage in http2-compat-serverresponse
Cesar-M-Diaz Oct 14, 2022
17ef1bb
lib: make properties on Blob and URL enumerable
KhafraDev Oct 14, 2022
cc2393c
lib: promise version of streams.finished call clean up
ntedgi Oct 15, 2022
5fce8e3
src: iwyu in cleanup_queue.cc
codebytere Oct 15, 2022
3519d74
test: improve test coverage for `os` package
juanarbol Oct 15, 2022
43677e5
test: skip test depending on `overlapped-checker` when not available
aduh95 Oct 15, 2022
e6bbc50
doc: improve the workflow to test release binaries
RafaelGSS Oct 15, 2022
7900810
meta: update AUTHORS
nodejs-github-bot Oct 16, 2022
025e616
tools: update lint-md-dependencies
nodejs-github-bot Oct 16, 2022
02cff4a
url: improve url.parse() compliance with WHATWG URL
Trott Oct 17, 2022
d47f832
doc: run license-builder
github-actions[bot] Oct 17, 2022
84e7388
url: improve port validation
Trott Oct 17, 2022
c1ca19f
test: update WPT resources
XadillaX Oct 10, 2022
a27c994
benchmark: add blob benchmark
anonrig Oct 17, 2022
5fbccae
doc: fix http and http2 writeEarlyHints() parameter
meyfa Oct 17, 2022
8b4a41e
lib: fix typo in `pre_execution.js`
aduh95 Oct 17, 2022
e8103fd
doc: updated security stewards
mhdawson Oct 14, 2022
24e24bd
build: add version info to timezone update PR
RaisinTen Oct 18, 2022
dbc696d
test: remove unnecessary noop function args to mustCall()
Trott Oct 18, 2022
3bfba6d
deps: patch V8 to 10.7.193.16
targos Oct 18, 2022
71b8d50
test: improve assertions in `test-repl-unsupported-option.js`
juanarbol Oct 18, 2022
2f7518a
deps: update timezone
nodejs-github-bot Oct 18, 2022
8662399
test: remove mentions of `--experimental-async-stack-tagging-api` flag
szuend Oct 18, 2022
2105f09
node-api,test: fix test_reference_double_free crash
vmoroz Oct 8, 2022
9ed9aa8
lib: add ability to add separate event name to defineEventHandler
jasnell Oct 19, 2022
d41f8ff
util: add MIME utilities (#21128)
bmeck Oct 19, 2022
a70b276
tools: do not use the set-output command in workflows
lpinca Oct 19, 2022
2ccc03e
tools: update gr2m/create-or-update-pull-request-action
lpinca Oct 19, 2022
8abc3f7
http: add priority to common http headers
jasnell Oct 17, 2022
17349a2
build: restore Windows resource file
richardlau Oct 19, 2022
2e5d8e7
esm: protect ESM loader from prototype pollution
aduh95 Oct 19, 2022
3db37e7
inspector: refactor `inspector/promises` to be more robust
aduh95 Oct 19, 2022
ec86830
meta: move one or more collaborators to emeritus
nodejs-github-bot Oct 19, 2022
9dc21a1
src: simplify ALPN code, remove indirection
bnoordhuis Oct 3, 2022
e5b1179
src: optimize ALPN callback
bnoordhuis Oct 3, 2022
b4bedde
doc: fix typo in parseArgs default value
tniessen Oct 20, 2022
26a2ae2
test: wrap missing `common.mustCall`
MoLow Oct 20, 2022
82e6043
test: mark test-watch-mode* as flaky on all platforms
pbo-linaro Oct 20, 2022
f0480d6
test: remove unnecessary noop function args to `mustCall()`
aduh95 Oct 20, 2022
17e86e4
test: remove experimental-wasm-threads flag
targos Oct 20, 2022
162bf0d
src: fix test runner coverage
MoLow Oct 20, 2022
a8412f5
src: forbid running watch mode in REPL
MoLow Oct 20, 2022
93a34fa
doc: update Node.js 16 End-of-Life date
richardlau Oct 21, 2022
c7b7f2b
lib: add lint rule to protect against `Object.prototype.then` pollution
aduh95 Oct 21, 2022
36acf8a
net: remove _readableState from debug statement
Trott Oct 21, 2022
66e1dc4
report,doc: define report version semantics
gireeshpunathil Oct 21, 2022
533e38b
doc: mark Node.js v17.x as EOL
climba03003 Oct 21, 2022
3e4033a
doc: fix display of "problematic" ASCII characters
Alhadis Oct 21, 2022
ee34a3a
doc: mention v18.x openssl maintaining guide
RafaelGSS Oct 21, 2022
9d449d3
doc: add note about latest GitHub release
targos Oct 22, 2022
809e8dc
doc: fix v14.x link maintaining openssl guide
RafaelGSS Oct 19, 2022
1655532
stream: don't push null from closed promise #42694
davedoesdev Oct 22, 2022
2b3b291
test: watch mode inspect restart repeatedly
MoLow Oct 22, 2022
5190021
doc: add major version note to release guide
ruyadorno Oct 18, 2022
c23e023
doc: be more definite and present tense-y
bnoordhuis Oct 23, 2022
7a31ae8
src,lib: retrieve parsed source map url from v8
legendecas Sep 26, 2022
732f9a7
trace_events: fix getCategories
theanarkh Oct 24, 2022
a2620ac
report: add rss and use/kernel cpu usage fields
theanarkh Oct 24, 2022
4e14ed8
src: remove unused `contextify_global_private_symbol`
daeyeon Oct 24, 2022
85cb4d7
doc: update mark release line lts on release guide
ruyadorno Oct 24, 2022
1bc84ce
url: remove \t \n \r in url.parse() similar to WHATWG
Trott Oct 24, 2022
0a6ed6f
Revert "deps: V8: forward declaration of `Rtl*FunctionTable`"
targos Oct 25, 2022
94b7f53
http2: fix debugStream method
santigimeno Oct 25, 2022
fabed9b
test: add test for Module._stat
RaisinTen Oct 25, 2022
c43bc21
tools: fix `create-or-update-pull-request-action` hash on GHA
aduh95 Oct 25, 2022
1635140
http2: fix crash on Http2Stream::diagnostic_name()
santigimeno Oct 25, 2022
8cda730
deps: update ICU to 72.1
targos Oct 25, 2022
b5baaa6
dns: fix port validation
aduh95 Oct 25, 2022
3a26347
doc: add lukekarrys to collaborators
lukekarrys Oct 25, 2022
b39dcde
test: remove a snapshot blob from test-inspect-address-in-use.js
daeyeon Oct 26, 2022
ff174b0
test_runner: add extra fields in AssertionError YAML
bengl Oct 26, 2022
3a1ee94
build: add GitHub token to auto-start-ci workflow
richardlau Oct 26, 2022
316354e
http2: improve session close/destroy procedures
santigimeno Oct 26, 2022
3c7ea23
test: fix typo in `test/parallel/test-fs-rm.js`
TimShilov Oct 26, 2022
54d8068
doc: mark Node.js 12 as End-of-Life
RafaelGSS Oct 26, 2022
bc0ae3e
stream: fix web streams have no Symbol.toStringTag
MrJithil Oct 26, 2022
a415869
tools: update V8 gypfiles for RISC-V
andreas-schwab Oct 26, 2022
8d56822
src: remap invalid file descriptors using `dup2`
obiwac Oct 26, 2022
d89ca1b
fs: trace more fs api
theanarkh Oct 26, 2022
916e876
doc: add link to triage guide
bmuenzenmeyer Oct 26, 2022
afa8291
test_runner: call {before,after}Each() on suites
cjihrig Oct 27, 2022
f589961
Revert "deps: make V8 compilable with older glibc"
targos Oct 27, 2022
5335e29
src: let http2 streams end after session close
santigimeno Oct 27, 2022
29b9f4f
build: remove unused language files
bnoordhuis Oct 23, 2022
36c5927
test,crypto: update WebCryptoAPI WPT
panva Oct 25, 2022
de2df55
doc: update process.release
panva Oct 25, 2022
8f8d7e7
doc: add bmuenzenmeyer to triagers
bmuenzenmeyer Oct 24, 2022
243c141
src: clarify OptionEnvvarSettings member names
legendecas Oct 27, 2022
f9bc40a
test: use uv_sleep() where possible
santigimeno Oct 27, 2022
f598edb
build: fix icu-small build with ICU 72.1
srl295 Oct 27, 2022
6e30d22
tools: update actions/setup-python to v4
anonrig Oct 27, 2022
40a5e22
esm: protect ESM loader from prototype pollution
aduh95 Oct 27, 2022
58bec56
doc: add more lts update steps to release guide
ruyadorno Oct 27, 2022
e60d905
stream: fix duplexify premature destroy
ronag Oct 23, 2022
dfe4237
perf_hooks: align toStringTag with other Web Performance implementations
daeyeon Oct 27, 2022
7225a7d
doc, http: add Uint8Array as allowed type
Flarna Oct 27, 2022
c179c14
doc: change make lint to make lint-md
RafaelGSS Oct 27, 2022
75e0a2d
build: workaround for node-core-utils
gengjiawen Oct 28, 2022
ad9a5bb
meta: move a collaborator to emeritus
Trott Oct 28, 2022
49be13c
tools: keep Emeriti lists case-insensitive alphabetic
Trott Oct 28, 2022
02ebde3
test: use common/tmpdir in watch-mode ipc test
richardlau Oct 28, 2022
0738d14
tools: fix `request-ci-failed` comment
aduh95 Oct 28, 2022
d9163f1
doc: clarify moderation in `onboarding.md`
benjamingr Oct 28, 2022
ddb7df7
test: deflake test-http2-empty-frame-without-eof
santigimeno Oct 27, 2022
7b938df
build: support Python 3.11
lpinca Oct 26, 2022
786f086
tools: use Python 3.11 in GitHub Actions workflows
lpinca Oct 26, 2022
069747b
test: fix timeout of test-heap-prof.js in riscv devices
Oct 29, 2022
b9039a5
doc: add history section to `fetch`-related globals
aduh95 Oct 29, 2022
aa4152a
src: fix `crypto.privateEncrypt` fails first time
liuxingbaoyu Oct 29, 2022
eed799b
test: improve test coverage in `test-event-capture-rejections.js`
juanarbol Oct 29, 2022
0040030
test_runner: report tap subtest in order
MoLow Oct 28, 2022
0d24163
deps: update undici to 5.12.0
nodejs-github-bot Oct 30, 2022
0d41df9
deps: update corepack to 0.15.0
nodejs-github-bot Oct 30, 2022
b41b5ba
meta: update AUTHORS
nodejs-github-bot Oct 30, 2022
42db849
src: call uv_library_shutdown before DisposePlatform
theanarkh Oct 28, 2022
0d58bb9
meta: remove dont-land-on-v12 auto labeling
MoLow Oct 30, 2022
f10f2c1
test: fix textdecoder test for small-icu builds
richardlau Oct 30, 2022
d7470ad
lib: fix `AbortSignal.timeout` parameter validation
dnalborczyk Oct 31, 2022
ccb1c1e
stream: add compose operator
rluvaton Oct 31, 2022
bfbfaca
meta: fix email address typo in README
Trott Oct 31, 2022
ba89cea
tools: update lint-md-dependencies
nodejs-github-bot Oct 31, 2022
1a04881
http: headers(Distinct), trailers(Distinct) setters to be no-op
sonimadhuri Oct 31, 2022
738144c
module: ensure relative requires work from deleted directories
bmeck Oct 31, 2022
97547bc
src: lock-free init_process_flags
kapouer Oct 31, 2022
34bfef9
fs: add recursive watch to linux
anonrig Oct 31, 2022
3369120
buffer: fix validation of options in `Blob` constructor
aduh95 Oct 31, 2022
670def3
fs: fix opts.filter issue in cpSync
thoqbk Nov 1, 2022
3e46ebd
src: trace threadpool event
theanarkh Nov 1, 2022
a866e8c
meta: update collaborator email address in README
Trott Nov 1, 2022
7428651
test: convert test-debugger-pid to async/await
lukekarrys Nov 1, 2022
e118dd8
tools: refactor dynamic strings creation in shell scripts
aduh95 Nov 1, 2022
daff3b8
fs: update todo message
anonrig Nov 1, 2022
8d7aa53
build,win: pass --debug-nghttp2 to configure
santigimeno Oct 27, 2022
5d48011
src: print nghttp2 logs when using --debug-nghttp2
santigimeno Oct 27, 2022
d5f4d98
test: make `test-eventemitter-asyncresource.js` shorter
juanarbol Nov 1, 2022
d172669
lib: fix TypeError when converting a detached buffer source
cola119 Nov 1, 2022
9d15da3
report: add more memory info
theanarkh Nov 2, 2022
7d7e7c3
doc: fix "task_processor.js" typo
Nov 3, 2022
2ee052f
tools: fix `request-ci-failed` comment
aduh95 Nov 3, 2022
b4b6b95
doc: update name of Node.js core Slack channel
Trott Nov 3, 2022
4e45585
src: revert is_release to 0
RafaelGSS Nov 4, 2022
9f3d2f6
lib: drop fetch experimental warning
mcollina Nov 5, 2022
2fcf851
os: convert uid and gid to 32-bit signed integers
lpinca Mar 16, 2022
43db0fb
test: fix test-socket-write-after-fin-error
lpinca Jul 12, 2022
7435284
lib: use process.nextTick() instead of setImmediate()
lpinca Sep 29, 2022
66e7821
test: defer invocation checks
lpinca Oct 25, 2022
bfe3819
deps: upgrade to libuv 1.44.2
lpinca Mar 15, 2022
4d38bf2
doc: add `node:` prefix for examples
daeyeon Nov 5, 2022
eda4ae5
tools: add automation for updating base64 dependency
facutuesca Nov 6, 2022
88c3bb6
meta: update AUTHORS
nodejs-github-bot Nov 6, 2022
44de232
deps: patch V8 to 10.7.193.20
targos Nov 6, 2022
5a1252d
doc: use module names in stability overview table
panva Nov 6, 2022
3de1257
doc: add more info for timer.setInterval
theanarkh Nov 6, 2022
97fe8ba
tools: increase macOS cores to 3 on GitHub CI
Trott Nov 6, 2022
0deed8d
util: improve textdecoder decode performance
anonrig Nov 6, 2022
326d19a
src: resolve TODO related to inspector CVEs
tniessen Nov 6, 2022
e275859
tools: fix stability index generation
aduh95 Nov 7, 2022
f35d562
deps: update corepack to 0.15.1
nodejs-github-bot Nov 7, 2022
a7c5f31
doc: run license-builder
github-actions[bot] Nov 7, 2022
63267df
tools: update lint-md-dependencies to [email protected]
nodejs-github-bot Nov 7, 2022
8e7f9de
test_runner: fix afterEach not running on test failures
MrJithil Nov 7, 2022
13fb05e
crypto: handle unsupported AES ciphers in webcrypto
panva Nov 7, 2022
1f0edde
crypto: handle more webcrypto errors with OperationError
panva Nov 7, 2022
a8e9015
lib: fix JSDoc issues
Trott Oct 30, 2022
4b71db1
tools: update eslint to 8.26.0
nodejs-github-bot Oct 30, 2022
920804d
test_runner: avoid swallowing of asynchronously thrown errors
fossamagna Nov 7, 2022
1432474
deps: upgrade npm to 8.19.3
npm-cli-bot Nov 7, 2022
4a80aff
test: fix catching failed assertion
pavelhoral Nov 7, 2022
d5e5c75
doc: fix test runner's only tests section header
cjihrig Nov 7, 2022
717db1d
test: skip test-fs-largefile if not enough disk space
Trott Nov 6, 2022
86e22b4
src: track contexts in the Environment instead of AsyncHooks
joyeecheung Nov 7, 2022
6158d74
test_runner: support function mocking
cjihrig Apr 4, 2022
aa875a4
tools: update eslint to 8.27.0
nodejs-github-bot Nov 8, 2022
c168cbf
deps: V8: cherry-pick 56816d76c121
shipujin Nov 8, 2022
ba45373
doc: fix email for Ashley
mhdawson Nov 8, 2022
0478e40
lib: add options to the heap snapshot APIs
joyeecheung Oct 13, 2022
d4aabb9
doc: include last security release date
juanarbol Nov 7, 2022
0e9bad9
doc: allow for holidays in triage response
mhdawson Nov 1, 2022
bf868fd
tls: add "ca" property to certificate object
bnoordhuis Nov 9, 2022
79f6bb0
benchmark: fix text-decoder benchmark
anonrig Nov 7, 2022
c9cf399
benchmark: add parameters to text-decoder benchmark
anonrig Nov 7, 2022
89390a6
util: improve text-decoder performance
anonrig Nov 7, 2022
76cbc07
tools: allow scripts to run from anywhere
lpinca Nov 9, 2022
9aa305f
tools: add documentation regarding our api tooling
ovflowd Nov 1, 2022
aaca54c
node-api: handle no support for external buffers
mhdawson Oct 25, 2022
58334a3
doc, async_hooks: improve and add migration hints
Flarna Nov 10, 2022
e8075fd
tools: add automation for updating acorn dependency
facutuesca Nov 10, 2022
e2181e0
lib: fix eslint early return
RafaelGSS Nov 10, 2022
0237cff
2022-11-14, Version 19.1.0 (Current)
RafaelGSS Nov 1, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
test_runner: support function mocking
This commit allows tests in the test runner to mock functions
and methods.

PR-URL: #45326
Reviewed-By: Moshe Atlow <[email protected]>
Reviewed-By: Matteo Collina <[email protected]>
  • Loading branch information
cjihrig authored and RafaelGSS committed Nov 10, 2022
commit 6158d740f39018ced4c068cff3c23f480b100486
360 changes: 360 additions & 0 deletions doc/api/test.md
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,89 @@ Otherwise, the test is considered to be a failure. Test files must be
executable by Node.js, but are not required to use the `node:test` module
internally.

## Mocking

The `node:test` module supports mocking during testing via a top-level `mock`
object. The following example creates a spy on a function that adds two numbers
together. The spy is then used to assert that the function was called as
expected.

```mjs
import assert from 'node:assert';
import { mock, test } from 'node:test';

test('spies on a function', () => {
const sum = mock.fn((a, b) => {
return a + b;
});

assert.strictEqual(sum.mock.calls.length, 0);
assert.strictEqual(sum(3, 4), 7);
assert.strictEqual(sum.mock.calls.length, 1);

const call = sum.mock.calls[0];
assert.deepStrictEqual(call.arguments, [3, 4]);
assert.strictEqual(call.result, 7);
assert.strictEqual(call.error, undefined);

// Reset the globally tracked mocks.
mock.reset();
});
```

```cjs
'use strict';
const assert = require('node:assert');
const { mock, test } = require('node:test');

test('spies on a function', () => {
const sum = mock.fn((a, b) => {
return a + b;
});

assert.strictEqual(sum.mock.calls.length, 0);
assert.strictEqual(sum(3, 4), 7);
assert.strictEqual(sum.mock.calls.length, 1);

const call = sum.mock.calls[0];
assert.deepStrictEqual(call.arguments, [3, 4]);
assert.strictEqual(call.result, 7);
assert.strictEqual(call.error, undefined);

// Reset the globally tracked mocks.
mock.reset();
});
```

The same mocking functionality is also exposed on the [`TestContext`][] object
of each test. The following example creates a spy on an object method using the
API exposed on the `TestContext`. The benefit of mocking via the test context is
that the test runner will automatically restore all mocked functionality once
the test finishes.

```js
test('spies on an object method', (t) => {
const number = {
value: 5,
add(a) {
return this.value + a;
},
};

t.mock.method(number, 'add');
assert.strictEqual(number.add.mock.calls.length, 0);
assert.strictEqual(number.add(3), 8);
assert.strictEqual(number.add.mock.calls.length, 1);

const call = number.add.mock.calls[0];

assert.deepStrictEqual(call.arguments, [3]);
assert.strictEqual(call.result, 8);
assert.strictEqual(call.target, undefined);
assert.strictEqual(call.this, number);
});
```

## `run([options])`

<!-- YAML
Expand Down Expand Up @@ -644,6 +727,281 @@ describe('tests', async () => {
});
```

## Class: `MockFunctionContext`

<!-- YAML
added: REPLACEME
-->

The `MockFunctionContext` class is used to inspect or manipulate the behavior of
mocks created via the [`MockTracker`][] APIs.

### `ctx.calls`

<!-- YAML
added: REPLACEME
-->

* {Array}

A getter that returns a copy of the internal array used to track calls to the
mock. Each entry in the array is an object with the following properties.

* `arguments` {Array} An array of the arguments passed to the mock function.
* `error` {any} If the mocked function threw then this property contains the
thrown value. **Default:** `undefined`.
* `result` {any} The value returned by the mocked function.
* `stack` {Error} An `Error` object whose stack can be used to determine the
callsite of the mocked function invocation.
* `target` {Function|undefined} If the mocked function is a constructor, this
field contains the class being constructed. Otherwise this will be
`undefined`.
* `this` {any} The mocked function's `this` value.

### `ctx.callCount()`

<!-- YAML
added: REPLACEME
-->

* Returns: {integer} The number of times that this mock has been invoked.

This function returns the number of times that this mock has been invoked. This
function is more efficient than checking `ctx.calls.length` because `ctx.calls`
is a getter that creates a copy of the internal call tracking array.

### `ctx.mockImplementation(implementation)`

<!-- YAML
added: REPLACEME
-->

* `implementation` {Function|AsyncFunction} The function to be used as the
mock's new implementation.

This function is used to change the behavior of an existing mock.

The following example creates a mock function using `t.mock.fn()`, calls the
mock function, and then changes the mock implementation to a different function.

```js
test('changes a mock behavior', (t) => {
let cnt = 0;

function addOne() {
cnt++;
return cnt;
}

function addTwo() {
cnt += 2;
return cnt;
}

const fn = t.mock.fn(addOne);

assert.strictEqual(fn(), 1);
fn.mock.mockImplementation(addTwo);
assert.strictEqual(fn(), 3);
assert.strictEqual(fn(), 5);
});
```

### `ctx.mockImplementationOnce(implementation[, onCall])`

<!-- YAML
added: REPLACEME
-->

* `implementation` {Function|AsyncFunction} The function to be used as the
mock's implementation for the invocation number specified by `onCall`.
* `onCall` {integer} The invocation number that will use `implementation`. If
the specified invocation has already occurred then an exception is thrown.
**Default:** The number of the next invocation.

This function is used to change the behavior of an existing mock for a single
invocation. Once invocation `onCall` has occurred, the mock will revert to
whatever behavior it would have used had `mockImplementationOnce()` not been
called.

The following example creates a mock function using `t.mock.fn()`, calls the
mock function, changes the mock implementation to a different function for the
next invocation, and then resumes its previous behavior.

```js
test('changes a mock behavior once', (t) => {
let cnt = 0;

function addOne() {
cnt++;
return cnt;
}

function addTwo() {
cnt += 2;
return cnt;
}

const fn = t.mock.fn(addOne);

assert.strictEqual(fn(), 1);
fn.mock.mockImplementationOnce(addTwo);
assert.strictEqual(fn(), 3);
assert.strictEqual(fn(), 4);
});
```

### `ctx.restore()`

<!-- YAML
added: REPLACEME
-->

Resets the implementation of the mock function to its original behavior. The
mock can still be used after calling this function.

## Class: `MockTracker`

<!-- YAML
added: REPLACEME
-->

The `MockTracker` class is used to manage mocking functionality. The test runner
module provides a top level `mock` export which is a `MockTracker` instance.
Each test also provides its own `MockTracker` instance via the test context's
`mock` property.

### `mock.fn([original[, implementation]][, options])`

<!-- YAML
added: REPLACEME
-->

* `original` {Function|AsyncFunction} An optional function to create a mock on.
**Default:** A no-op function.
* `implementation` {Function|AsyncFunction} An optional function used as the
mock implementation for `original`. This is useful for creating mocks that
exhibit one behavior for a specified number of calls and then restore the
behavior of `original`. **Default:** The function specified by `original`.
* `options` {Object} Optional configuration options for the mock function. The
following properties are supported:
* `times` {integer} The number of times that the mock will use the behavior of
`implementation`. Once the mock function has been called `times` times, it
will automatically restore the behavior of `original`. This value must be an
integer greater than zero. **Default:** `Infinity`.
* Returns: {Proxy} The mocked function. The mocked function contains a special
`mock` property, which is an instance of [`MockFunctionContext`][], and can
be used for inspecting and changing the behavior of the mocked function.

This function is used to create a mock function.

The following example creates a mock function that increments a counter by one
on each invocation. The `times` option is used to modify the mock behavior such
that the first two invocations add two to the counter instead of one.

```js
test('mocks a counting function', (t) => {
let cnt = 0;

function addOne() {
cnt++;
return cnt;
}

function addTwo() {
cnt += 2;
return cnt;
}

const fn = t.mock.fn(addOne, addTwo, { times: 2 });

assert.strictEqual(fn(), 2);
assert.strictEqual(fn(), 4);
assert.strictEqual(fn(), 5);
assert.strictEqual(fn(), 6);
});
```

### `mock.method(object, methodName[, implementation][, options])`

<!-- YAML
added: REPLACEME
-->

* `object` {Object} The object whose method is being mocked.
* `methodName` {string|symbol} The identifier of the method on `object` to mock.
If `object[methodName]` is not a function, an error is thrown.
* `implementation` {Function|AsyncFunction} An optional function used as the
mock implementation for `object[methodName]`. **Default:** The original method
specified by `object[methodName]`.
* `options` {Object} Optional configuration options for the mock method. The
following properties are supported:
* `getter` {boolean} If `true`, `object[methodName]` is treated as a getter.
This option cannot be used with the `setter` option. **Default:** false.
* `setter` {boolean} If `true`, `object[methodName]` is treated as a setter.
This option cannot be used with the `getter` option. **Default:** false.
* `times` {integer} The number of times that the mock will use the behavior of
`implementation`. Once the mocked method has been called `times` times, it
will automatically restore the original behavior. This value must be an
integer greater than zero. **Default:** `Infinity`.
* Returns: {Proxy} The mocked method. The mocked method contains a special
`mock` property, which is an instance of [`MockFunctionContext`][], and can
be used for inspecting and changing the behavior of the mocked method.

This function is used to create a mock on an existing object method. The
following example demonstrates how a mock is created on an existing object
method.

```js
test('spies on an object method', (t) => {
const number = {
value: 5,
subtract(a) {
return this.value - a;
},
};

t.mock.method(number, 'subtract');
assert.strictEqual(number.subtract.mock.calls.length, 0);
assert.strictEqual(number.subtract(3), 2);
assert.strictEqual(number.subtract.mock.calls.length, 1);

const call = number.subtract.mock.calls[0];

assert.deepStrictEqual(call.arguments, [3]);
assert.strictEqual(call.result, 2);
assert.strictEqual(call.error, undefined);
assert.strictEqual(call.target, undefined);
assert.strictEqual(call.this, number);
});
```

### `mock.reset()`

<!-- YAML
added: REPLACEME
-->

This function restores the default behavior of all mocks that were previously
created by this `MockTracker` and disassociates the mocks from the
`MockTracker` instance. Once disassociated, the mocks can still be used, but the
`MockTracker` instance can no longer be used to reset their behavior or
otherwise interact with them.

After each test completes, this function is called on the test context's
`MockTracker`. If the global `MockTracker` is used extensively, calling this
function manually is recommended.

### `mock.restoreAll()`

<!-- YAML
added: REPLACEME
-->

This function restores the default behavior of all mocks that were previously
created by this `MockTracker`. Unlike `mock.reset()`, `mock.restoreAll()` does
not disassociate the mocks from the `MockTracker` instance.

## Class: `TapStream`

<!-- YAML
Expand Down Expand Up @@ -979,6 +1337,8 @@ added:
[`--test-name-pattern`]: cli.md#--test-name-pattern
[`--test-only`]: cli.md#--test-only
[`--test`]: cli.md#--test
[`MockFunctionContext`]: #class-mockfunctioncontext
[`MockTracker`]: #class-mocktracker
[`SuiteContext`]: #class-suitecontext
[`TestContext`]: #class-testcontext
[`context.diagnostic`]: #contextdiagnosticmessage
Expand Down
Loading