Skip to content

Instantly share code, notes, and snippets.

@leadegroot
Created April 15, 2017 23:24
Show Gist options
  • Save leadegroot/f37753b9e24639f84e336b3520a290d6 to your computer and use it in GitHub Desktop.
Save leadegroot/f37753b9e24639f84e336b3520a290d6 to your computer and use it in GitHub Desktop.
Use nightwatchjs to get some content from a webpage and store it in a cookie
var urlTest = 'https://example.com/';
var resultsCountCookieName = 'myCookie';
module.exports = {
'@tags': ['exampletagname'],
'Get Value from webpage into cookie' : function (client) {
// a week seems a suitable length of time to have the cookie last...
var maxAgeSeconds = 7 * 24 * 60 * 60 * 1000;
var todaysDate = new Date();
var expiryDate = new Date(todaysDate.getTime() + maxAgeSeconds);
// common uql checks
client
.url(urlTest)
// did we get a page? (basic sanity tests)
.assert.elementPresent('html', 'a base html element is present')
.assert.elementPresent('body', 'a body element is present')
// sleep to let the actual content load!
.pause(5000)
// delete any pre-existing cookie
.deleteCookie(resultsCountCookieName)
// get the contents of the element (my original was getting a numeric result from a page, which had commas in it and then had some words after that needed to be removed)
.assert.elementPresent('.results-count')
.getText('.results-count', function(result) {
resultCount = 0;
var spaceLocation = result.value.indexOf(" ");
if (spaceLocation !== -1) {
resultCount = result.value
.substr(0, spaceLocation) // the chars before the first space is the numeric record count
.trim()
.replace(/,/g, ""); // remove commas so we have an integer
}
})
.perform(function () {
client.setCookie({
name : resultsCountCookieName,
value : resultCount,
expires: expiryDate.toUTCString(),
max_age: maxAgeSeconds,
domain: "example.com",
secure: true,
httpOnly: false
})
})
// confirm we created a cookie
.getCookie(resultsCountCookieName, function callback(result) {
client.assert.equal(result.name, resultsCountCookieName);
client.assert.equal(result.value, resultCount);
})
.end();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment