Test runner
mock.method()
Replaces a method on a controlled object with an instrumented mock. Restore it after the test to avoid contaminating other work; prefer a test context mock tracker for test-scoped lifetime. Tested on Node.js 22.16.0. Example output (one line per entry): ["9 1", "1"].
Formal Syntax & Structure
nodejs syntaxnodejs
mock.method(object, methodName[, implementation][, options])Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| object | object | Object owning the method. |
| methodName | string | symbol | Method property. |
| implementation | Function | Replacement. |
| options | object | Mock options. |
Return Value
Function
Instrumented method.
Working Example
Example Snippetnodejs
import { mock } from 'node:test';const repo = { count: () => 1 };const f = mock.method(repo, 'count', () => 9);try { console.log(repo.count(), f.mock.callCount());}finally { mock.restoreAll();}console.log(repo.count());