Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using sinon.js sinon.stub() or sinon.spy() does not work with global functions in Safari #11

Open
ghost opened this issue Apr 8, 2015 · 0 comments

Comments

@ghost
Copy link

ghost commented Apr 8, 2015

I have run into an issue with global functions and trying to stub or spy on them with sinon.js. It seems that whatever the Safari launcher is doing to start Safari makes it so that there are two instances of global functions.

For example, if I create a function like so:

function myFunc() {
  return true;
}

console.log(window.myFunc === myFunc);  //-> true

Then use sinon to stub or spy that function, there are now two instances of myFunc.

sinon.stub(window, 'myFunc');  // spying has the same problem

console.log(window.myFunc === myFunc);  //-> false

The myFunc function does not get stubbed, but the window.myFunc function does. This causes problems as calls to myFunc will still call the original function and not the stubbed one.

I have created a few test cases to demonstrate the problem. This jsFiddle shows that on all browsers including Safari, using just qunit and sinon.js and stubbing a global function behaves as expected.

I also created two test repositories using karma, one that uses Jasmine and the other that uses Mocha, to test the exact same code. In both cases, the test fail in Safari after stubbing the global function.

I've had to get around this issue by stubbing out the window function, then making the non-window function equal to the the window function. Then when I restore the function, I have to make the non-window function equal to the window function.

describe('test', function() {

  beforeEach(function() {
    sinon.stub(window, 'myFunc');
    myFunc = window.myFunc;
  });

  afterEach(function() {
    myFunc.restore();  // this actually doesn't restore the myFunc function, only window.myFunc
    myFunc = window.myFunc;
  });

});
@ghost ghost changed the title Using sinon.js sinon.stub() or sinon.spy() does not work with global functions Using sinon.js sinon.stub() or sinon.spy() does not work with global functions in Safari Apr 8, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

0 participants