sinonjs / sinon

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

Sinon stub MomentJS cant stub main function #2518

Closed t1a2l closed 1 year ago

t1a2l commented 1 year ago

Describe the bug momentjs: /**

it isa function and also a namespace, cant seem to be able to stub the function.

To Reproduce const moment = require('moment'); const sandbox = sinon.createSandbox(); sandbox.stub(moment, "moment").callsFake(function(item) { return item; });

Expected behavior function idetified and result should appear inside item

Context (please complete the following information):

Additional context getting error : TypeError: Cannot stub non-existent property moment

fatso83 commented 1 year ago

You are trying to stub a property 'moment' of the moment namespace. AFAIK, you are rightly told that doesn't work, given that the typings are correct, so this does not seem like an issue with Sinon, but rather how to use it 😄

We are trying to keep the GitHub issues list tidy and focused on bugs and feature discussions. This ticket looks like a usage question; please post it to StackOverflow and tag it with sinon, so the bigger community can help answer your questions.

If you feel that your topic is an issue with Sinon, please open a new ticket and follow the guidelines for reporting an issue.

t1a2l commented 1 year ago

@fatso83 moment is a function within the moment library, it is like the main function, I wonder if it is somehow connected to another issue with utility functions here "https://github.com/sinonjs/sinon/issues/562" it seems like a bug rather then a usage issue.

fatso83 commented 1 year ago

No, moment is not a function within the moment library. The moment module is both a function and a namespace. As a function is an object, you can attach any number of props to it.

When you do sinon.stub(moment, 'moment') you are trying to wrap moment.moment, and as you can see there are no fields on the namespace called moment. The exports are all constants or utility functions:

image

Now, for your issue, what you want to do is basically replace the entire moment library during module loading. That is not something Sinon does. We can modify exports on the libraries, but we do not try to affect linking level operations. That is typically left to rewire, proxyquire, or my favorite: Quibble (of TestDouble), since it has native ES Module support

See this small article for tips on how to do this: https://sinonjs.org/how-to/link-seams-commonjs/