Is there a way to force a stub that is called with `new` to return some fake value?

147 views
Skip to first unread message

Michael Parker

unread,
Aug 9, 2016, 2:07:20 PM8/9/16
to Sinon.JS
Let's say I have a function that looks like this:


    function a() {
this.foo = 'bar';
return 'foo';
}


When invoked as a constructor `new a()`, this function will return `{foo: 'bar'}`

When invoked as a function `a()`, this function will return "foo"

If I were to stub this function like so:


    sinon.stub(window, 'a').returns('bar');


Then, invoking the function like `a()` would return "bar", and invoking the function as a constructor `new a()` would return an empty object.

Is there a way to force this stub of my `a` function to return a value when it is invoked with the `new` keyword?  Something like:


    sinon.stub(window, 'a').whenCalledWithNew().returns({bar: 'foo'});


So that when I do `new a()`, it would return `{bar: 'foo'}` instead of an empty object?

Thanks

Maximilian Antoni

unread,
Aug 13, 2016, 1:13:03 PM8/13/16
to sin...@googlegroups.com
No, your original function will always return "foo" and never an object, regardless of whether you call it with new. This is per the language spec and behavior is consistent across engines. Try it in any console ;-)

Cheers
-Max
--
You received this message because you are subscribed to the Google Groups "Sinon.JS" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sinonjs+u...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Michael Parker

unread,
Sep 1, 2016, 11:40:15 AM9/1/16
to Sinon.JS

It seems to work exactly as I described it in Chrome's console.


Michael Parker

unread,
Sep 1, 2016, 11:47:11 AM9/1/16
to Sinon.JS
Node v4.3 seems to have this behavior as well:


Regardless of what this function is supposed to return, is it possible to use Sinon to change a stub's return value of it was invoked with the `new` operator?

Kishore Indraganti

unread,
Oct 4, 2017, 6:49:43 PM10/4/17
to Sinon.JS
Did you got workaround for this ?
Reply all
Reply to author
Forward
0 new messages