Sinon stub callsFake argument

Kousha picture Kousha · May 18, 2017 · Viewed 11.4k times · Source

I had the following stubs running perfectly before

sinon.stub(console, 'log', () => {
    // Check what the arguments holds 
    // And either console.info it or do nothing
});

For example, adding console.info(arguments) inside there, would show me whatever console.log was getting.

With version 2xx I switched to callsFake:

sinon.stub(console, 'log').callsFake(() => {
    // Check what the arguments holds
    // And either console.info it or do nothing
});

This now longer works. console.info(arguments) has bazaar values, and nothing to do with what console.log is passing.

What am I doing wrong?!

Answer

philipisapain picture philipisapain · Feb 13, 2018

The arrow function you're passing to callsFake doesn't receive the arguments object as you would normally expect in a regular function.

From MDN

An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target.

Either change your arrow function to a regular anonymous function (function() {...}) or use the spread operator to explicitly unpack the arguments:

sinon.stub(console, 'log')
console.log.callsFake((...args) => {
  console.info(args)
});