frontend-challenges icon indicating copy to clipboard operation
frontend-challenges copied to clipboard

109 - jest.spyOn - javascript

Open jsartisan opened this issue 1 year ago • 0 comments

index.js

export function spyOn(obj, methodName) {
  const originalMethod = obj[methodName];
  const spy = {
    calls: [],
    results: [],
    restore: function () {
      obj[methodName] = originalMethod;
    },
  };

  obj[methodName] = function (...args) {
    spy.calls.push(args);

    const result = originalMethod.apply(obj, args);
    spy.results.push(result);

    return result;
  };

  return spy;
}

jsartisan avatar Jul 08 '24 14:07 jsartisan