sinonjs / sinon

Test spies, stubs and mocks for JavaScript.

Home Page:https://sinonjs.org/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Sinon stub MomentJS cant stub main function

t1a2l opened this issue · comments

commented

Describe the bug
momentjs:
/**

  • @param strict Strict parsing disables the deprecated fallback to the native Date constructor when
  • parsing a string.
    */
    declare function moment(inp?: moment.MomentInput, strict?: boolean): moment.Moment;
    export = moment;
    export as namespace moment;

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):

  • Library version: 15.1.0
  • Environment: VS code windows 10
  • Other libraries you are using: momentjs

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

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.

commented

@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 "#562" it seems like a bug rather then a usage issue.

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/