jasmine mock window object

The problem is that you just overwrite a property of the window object. And if you can do that, the browser can do that as well. So mocking a function or property of a global object that everyone can access isn’t a good idea in general, because you can never be sure that your changes will be there when you try to access them.

Which brings me to dependency injection. Its a common pattern to make your code unit testable, with a focus on unit. Whats does it mean. When ever you create a new object or access a global object, you’re not only testing your unit functionality, but also the functionality of your newly created or global object. To prepend that, you not create the new objects in your unit, but pass them into. Normally you would to this in the constructor, but as in JavaScript function are objects with the function body as constructor, you can also pass the dependencies simply into your function.

So in your case, the function depends on the global window object. So instead of trying to access the global window object, pass it as a parameter into your function. Doing it this way you can pass in the window object in your production code and a simple JavaScript object with an arguments atribute into your test:

function youWannaTest(w){
    console.log(w.arguments[0]);
}

In your extension call the function like this:

youWannaTest(window);

In your test call the function like this:

youWannaTest({arguments: ['someValue']});

Leave a Comment