sinonjs / sinon

Test spies, stubs and mocks for JavaScript.
https://sinonjs.org/
Other
9.64k stars 771 forks source link

Discrepancy in stub construction methods #2574

Closed weshouman closed 9 months ago

weshouman commented 9 months ago

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

Additional context

weshouman commented 9 months ago

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.

fatso83 commented 9 months ago

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?

weshouman commented 9 months ago

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

Issue:

Fix:

fatso83 commented 9 months ago

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.