Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test javascript redirection without redirecting?

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?

like image 357
Mario Avatar asked May 27 '11 14:05

Mario


People also ask

How do I post 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.

How do I redirect without JavaScript?

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.

What is JavaScript 301 redirect?

“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.”


1 Answers

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.

like image 73
Morgan ARR Allen Avatar answered Oct 14 '22 14:10

Morgan ARR Allen