sinon icon indicating copy to clipboard operation
sinon copied to clipboard

Stub doesn't return the correct value when used with new

Open Rhysjc opened this issue 7 years ago • 7 comments

  • Sinon version : 4.2.1
  • Environment : Node 6.10.3

What did you expect to happen? Stub to return the correct value when used with new.

What actually happens Returns a function

How to reproduce

const stub = sinon.stub().returns('a value');
console.log(stub()); // 'a value'
console.log(new stub()); // 'functionStub {}'

Rhysjc avatar Jan 26 '18 09:01 Rhysjc

In case you want to scratch your own itch, here is the piece of code where I would start looking into it:

https://github.com/sinonjs/sinon/blob/a8171c3441869002bb61e4ef22eb4b72d67da72e/lib/sinon/spy.js#L197-L204

mantoni avatar Jan 26 '18 11:01 mantoni

I can reproduce this. I was using a Symbol in returns but after looking at the code only objects are supported. So my workaround is to use an empty object instead of a symbol to indicate the the correct value is passed through some calls.

lo1tuma avatar Feb 20 '18 19:02 lo1tuma

Is there a way around this since "new" keyword is like default with ES6 can it support stubs themselves with objects.. EG: const returnStub = sinon.stub(); const stub = sinon.stub().returns(returnStub);

LRagji avatar Mar 18 '20 14:03 LRagji

since "new" keyword is like default with ES6 can it support stubs themselves with objects..

I am sorry, but I do not understand what this means. Can you elaborate on what you mean? I especially do not understand what you mean by saying "new is like default with ES6".

fatso83 avatar Mar 18 '20 15:03 fatso83

Sorry i wrote in jiffy, I was trying to do following

const instanceStub = sinon.stub(); 
const type = sinon.stub();
type.returns(instanceStub);
const instance = new type();
console.log(instance); //prints proxy function, expecting instanceStub

The above failed if instanceStub was a Stub but if instanceStub is normal object then it passed.

LRagji avatar Mar 18 '20 17:03 LRagji

I am guessing returnStub is supposed to be instanceStub? In any case, seeing that this issue is over 2 years old, I think it is quite likely that this will only happen when someone that is affected takes a stab at doing it ... Max gave some good hints at where to start a change. We are very friendly and accept pull requests 😺

Here's how to start

fatso83 avatar Mar 19 '20 09:03 fatso83

Corrected code, ohh i saw the date now 🙂

LRagji avatar Mar 19 '20 11:03 LRagji

The only issue I really see here is that we should perhaps be stricter about what we accept as a return value when newing objects. The only meaningful thing to return when invoking with new is an object, so the current implementation is correct when forcing it to be the thisValue.

TBH, I think an improvement would be to throw with a meaningful error message when encountering return values that are not objects, as that does not make sense.

fatso83 avatar Aug 09 '23 08:08 fatso83