1

Is it possible to create a Spy function that returns an object that keeps track of how many times a function is called like shown below?

var spy = Spy(console, 'error')

console.error('calling console.error')
console.error('calling console.error')
console.error('calling console.error')

console.log(spy.count) // 3
1
  • maybe you need to implement a console.log by yourself Commented Oct 1, 2022 at 5:21

2 Answers 2

1

You could wrap the call to the method

class Spy {
  constructor(obj, method) {
    this.count = 0

    const _method = obj[method] // save the ref to the original method
    const self = this

    // wrap the method call with additional logic
    obj[method] = function () {
      self.count++
      _method.call(this, ...arguments)
    }
  }
}

var spy = new Spy(console, "error")

console.error("calling console.error")
console.error("calling console.error")
console.error("calling console.error")

console.log(spy.count) // 3

Sign up to request clarification or add additional context in comments.

1 Comment

beautiful , thanks
0

you can use javascript Clouser property.

// Initiate counter
let counter = 0;

// Function to increment counter
function add() {
  counter += 1;
}

// Call add() 3 times
add();
add();
add();

// The counter should now be 3

reference https://www.w3schools.com/js/js_function_closures.asp

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.