sinonjs / sinon

Test spies, stubs and mocks for JavaScript.

Home Page:https://sinonjs.org/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Discrepancy in stub construction methods

weshouman opened this issue · comments

Describe the bug

Creating an anonymous stub, does not always allow restoration

URL.createObjectURL = sinon.stub().returns('mock-url');
console.log(URL.createObjectURL.restore); // prints undefined

While stubbing by passing the object and function name allows restoration

sinon.stub(URL, 'createObjectURL').returns('mock-url');
console.log(URL.createObjectURL.restore); // prints function

To Reproduce

Run the aforementioned snippets

Expected behavior

Based on the stubs documentation, there are no differences mentioned between both, so is the assignment method not supported and the documentation is to be updated, or this is a bug to be fixed

Screenshots
NA

  • Library version: 17.0.1

Additional context

The default constructor would create a stub that overwrites the original object unknowing about how to restore it.
The stub would work, but a function like restore requires pre-knowledge of the original function behaviour, thus it won't be available.
The current implementation does not provide a restore function for the stubs created by the default constructor, thus the undefined value.

This was closed, but it looks like you wanted a new feature? Not a bug, but missing functionality? Could you describe how you wanted it to look?

This issue was mainly due to a confusion, if something would be updated may be it's the doc part.
Scenario:

  • A stub function was being assigned to a stub object.
  • After finishing the tests all the stubbed methods were being restored.

Issue:

  • The restore() method is undefined for stubs that are created with the default constructor ( note: we can only stub using the default constructor in this case, as stub(obj, 'function') requires the 'function' to be predefined).

Fix:

  • Check if the restore() is defined for the stubbed method before calling it.

Ah, I get you. There is no way to fix this, as a function in itself does not know which name it is assigned to, so a restore function would not know what to do with this.