I have the following function
var redirect = function() {
window.location.href = "http://www.google.com";
}
I want to test this function using qUnit.
The problem is, when I call up the HTML document in which my tests run, as soon as it gets to the test that calls redirect()
, the browser loads google.com. What I would like to do is mock out window.location.href somehow so that it doesn't redirect, and so I can check that it was set to the proper value.
Rewriting this in a manner that it would be more testable would be an acceptable answer and is welcomed. Since I am using qUnit, some jQuery magic would be appropriate, as would some old fashioned refactoring. Adding a custom setter for window.location.href was suggested, but I couldn't figure out how to get this to work.
Please, no suggestions of changing the behavior of my code.
Here's how I ended up solving it.
giggity.navOnChange
is the function analogous toredirect
in the original question.Code:
Test code:
I'm using the
giggity
object as a namespace for my code. I assign thegiggity.window
variable to point towindow
, and interact withwindow
viagiggity.window
. This way, I can easily mock out any manipulation of thewindow
object. I pointgiggity.window
to a mock object, call the function that modifiesgiggity.window
and check the value of the mock.You can't modify window.location.href without reloading the page. But if you absolutely want to test these kind of functions it requires a bit of logic modification.
Example #1:
You could do this with two functions, one can be simple redirectTo function similar to yours, and the other can be the one that has the logic of building and url. Like this:
Example #2:
You can also write a cross-between these two:
The above example will have the similar form as your original function, but having the URL building logic function that you can actually test.
Not an example, but #3:
On the other hand if you don't want to change your logic and you have a function simple as this it's no biggie if you just don't test it...
What you are looking to do is best done at integration or acceptance test level, not unit test level. Otherwise you end up with fake browsers and then you are not testing real world, and not really testing anything.
You can open up and iframe on the same domain as the tests and load your code in there. Then you will be able to assert with asynchronous tests.
However qUnit doesn't really seem to have all the tools you would need for that, so if you are looking to test more than a few things that require page reload/navigation, you should use a different testing tool.
The alternative as other posters have mentioned is to mock out the location object and test the behaviour of your code (rather than the browser).