karma-runner / karma-safari-launcher

A Karma plugin. Launcher for Safari.
MIT License
19 stars 17 forks source link

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

Open ghost opened 9 years ago

ghost commented 9 years ago

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;
  });

});