Skip to content

Instantly share code, notes, and snippets.

@chrisirhc
Last active December 17, 2015 03:29
Show Gist options
  • Save chrisirhc/5543862 to your computer and use it in GitHub Desktop.
Save chrisirhc/5543862 to your computer and use it in GitHub Desktop.
Self-redirecting page

Example 3 (Anti-pattern)

Self-redirecting page

Please don't do this!

A self-redirect initiated by the JavaScript to a page can make it very difficult to write a test for that page.

The test script is unable to determine whether the page has completed the redirect without checking the url.

Goal

In this example, try to write a test to get the "Horray" message.


Example script:

click | css=button
waitForCondition | selenium.getText('css=button') == "Done" | 10000
click | css=button
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<button id="go">
Go
</button>
<div id="result"></div>
</body>
</html>
/* global $ */
var redirectTimer;
var ready = false;
var someSpecialString = '?hello';
if (window.location.search != someSpecialString) {
// Simulate some random loading time here
redirectTimer = setTimeout(function () {
// Redirect!
window.location.search = someSpecialString;
}, Math.random()*1000);
} else {
// If this page was already redirected, set it to ready
ready = true;
}
$(function () {
$('#go').on('click', function () {
// Cancel redirect if this is clicked
clearTimeout(redirectTimer);
if (ready) {
$('#result').text('Hooray!');
} else {
$('#result').text('Boohoo :(');
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment