sinon
sinon copied to clipboard
Stub doesn't return the correct value when used with new
- 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 {}'
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
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.
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);
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".
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.
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 😺
Corrected code, ohh i saw the date now 🙂
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.