MCPcopy Create free account
hub / github.com/nodejs/node / method

Method method

lib/internal/test_runner/mock/mock.js:473–550  ·  view source on GitHub ↗

* Creates a method tracker for a specified object or function. * @param {(object | Function)} objectOrFunction - The object or function containing the method to be tracked. * @param {string} methodName - The name of the method to be tracked. * @param {Function} [implementation] - An optiona

(
    objectOrFunction,
    methodName,
    implementation = kDefaultFunction,
    options = kEmptyObject,
  )

Source from the content-addressed store, hash-verified

471 * @returns {ProxyConstructor} The mock method tracker.
472 */
473 method(
474 objectOrFunction,
475 methodName,
476 implementation = kDefaultFunction,
477 options = kEmptyObject,
478 ) {
479 validateStringOrSymbol(methodName, 'methodName');
480 if (typeof objectOrFunction !== 'function') {
481 validateObject(objectOrFunction, 'object');
482 }
483
484 if (implementation !== null && typeof implementation === 'object') {
485 options = implementation;
486 implementation = kDefaultFunction;
487 }
488
489 validateFunction(implementation, 'implementation');
490 validateObject(options, 'options');
491
492 const {
493 getter = false,
494 setter = false,
495 times = Infinity,
496 } = options;
497
498 validateBoolean(getter, 'options.getter');
499 validateBoolean(setter, 'options.setter');
500 validateTimes(times, 'options.times');
501
502 if (setter && getter) {
503 throw new ERR_INVALID_ARG_VALUE(
504 'options.setter', setter, "cannot be used with 'options.getter'",
505 );
506 }
507 const descriptor = findMethodOnPrototypeChain(objectOrFunction, methodName);
508
509 let original;
510
511 if (getter) {
512 original = descriptor?.get;
513 } else if (setter) {
514 original = descriptor?.set;
515 } else {
516 original = descriptor?.value;
517 }
518
519 if (typeof original !== 'function') {
520 throw new ERR_INVALID_ARG_VALUE(
521 'methodName', original, 'must be a method',
522 );
523 }
524
525 const restore = { __proto__: null, descriptor, object: objectOrFunction, methodName };
526 const impl = implementation === kDefaultFunction ?
527 original : implementation;
528 const ctx = new MockFunctionContext(impl, restore, times);
529 const mock = this.#setupMock(ctx, original);
530 const mockDescriptor = {

Callers 2

getterMethod · 0.95
setterMethod · 0.95

Calls 4

#setupMockMethod · 0.95
validateStringOrSymbolFunction · 0.85
validateTimesFunction · 0.85

Tested by

no test coverage detected