I'm using Jasmine for some testing, although this can be generally applied to browser-based javascript unit testing.
I have a function that, on certain conditions redirects the user to a different page using window.location.assign
. The problem is, if this line is reached, the page is redirected. In this case, since it's redirected to '/'
, the page reloads, and all the tests run again. What can I do to test that the function reaches the line where it redirects, without redirecting?
To submit an HTML form without redirection, we can redirect to an invisible iframe. And then we set the form's target attribute to the ID of the hidden iframe to redirect to it after form submission is done.
To redirect from an HTML page, use the META Tag. With this, use the http-equiv attribute to provide an HTTP header for the value of the content attribute. The value of the content is the number of seconds; you want the page to redirect after.
“If you need to change the URL of a page as it is shown in search engine results, we recommend that you use a server-side 301 redirect. This is the best way to ensure that users and search engines are directed to the correct page. The 301 status code means that a page has permanently moved to a new location.”
I have faced this same problem. My solution was to break out the actual redirect into a single purpose function. That is, don't do any condition checking or other logic, just redirect. Say this is the old code...
function redirect() {
if(something) {
window.location = "/";
else if(somethingElse)
window.location = "/?a=42";
else
window.location = "/derp";
}
I would change that to..
function redirect() {
if(something) {
doRedirect("/");
else if(somethingElse)
doRedirect("/?a=42");
else
doRedirect("/derp");
}
function doRedirect(href) {
window.location = href;
}
Then you can spyOn
the doRedirect
function to ensure the redirect function is passing in the correct URI for the conditions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With