0

I try to stub any global function: function randomNumber(min, max){/*...*/} (window.randomNumber === randomNumber) but when I create stub in test case sinon.stub(window, 'randomNumber') and mocks result randomNumber.returns(1);) it doesn't work and call original 'randomNumber' (window.randomNumber !== randomNumber), why?


[EDIT]

Part of my code: https://plnkr.co/edit/GAaxA3iN8QehDN7HbOc8?p=preview (it is interesting it's works in browser, in console throw undefined is not a function (evaluating 'randomNumber.onCall(0)')) and package.json:

"chai": "^3.5.0", "karma": "^1.7.0", "karma-mocha": "^1.3.0", "karma-phantomjs-launcher": "^1.0.4", "karma-sinon-chai": "^1.3.1", "mocha": "^3.4.1", "phantomjs-prebuilt": "^2.1.14", "sinon": "^2.2.0", "sinon-chai": "^2.10.0", "sinon-stub-promise": "^4.0.0"

Alcadur
  • 681
  • 1
  • 8
  • 22
  • Check that `window.randomNumber` can be overridden in principle and report to us here in comments. – ilyaigpetrov May 16 '17 at 12:41
  • I can't override `window.randomNumber` after stub created – Alcadur May 16 '17 at 12:51
  • 1) `const originalRandomNumber = window.randomNumber`. 2) `window.randomNumber = function () { console.log("Overridden!") }`. 3) `console.log(window.randomNumber === originalRandomNumber)`. <- If it prints `false` then it was overridden (without `sinon` yet). What does it print? – ilyaigpetrov May 16 '17 at 12:56
  • I create blank test case and paste there steps above, it prints `false`. – Alcadur May 17 '17 at 05:18
  • Write a minimal script that reproduces your issue and add it to the question, also add what packages w/ versions it needs to work, so we may reproduce it and troubleshoot. – ilyaigpetrov May 17 '17 at 13:03
  • I added code and package.json dependencies – Alcadur May 18 '17 at 06:06
  • In Node.js: 1) there is no `window` object, 2) calling `randomNumber` is identical to calling `global.randomNumber` not `window.randomNumber` as it is in browser. `randomNumber` is undefined in Node, because `randomNumber` is not the same as `window.randomNumber`. You may share your __Node.js__ code via https://runkit.com – ilyaigpetrov May 18 '17 at 06:28
  • 1
    Yes, but when I run tests in phantomjs, window object is defined – Alcadur May 18 '17 at 07:23
  • Someone sorted this out? @Alcadur? I'm facing the same issue right now after upgrading Karma/Sinon/etc to latest version. I do `sinon.stub(window, 'foo').value(123)` but then from my JS code using `foo` yields `undefined`, although using `window.foo` correctly gives `123` but i'm not going to rewrite my whole codebase... – diegocr Jun 01 '19 at 13:47

0 Answers0