Last active
August 29, 2015 14:16
-
-
Save tildedave/c3e821769254dc5a6556 to your computer and use it in GitHub Desktop.
Custom assertion for Nightwatch to see if a link has the expected text and destination
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var util = require('util'); | |
exports.assertion = function(selector, text, href, msg) { | |
var DEFAULT_MSG = 'Testing if link <%s> contains text <%s> and ends with href <%s>".'; | |
var MSG_ELEMENT_NOT_FOUND = DEFAULT_MSG + ' ' + '<%s> could not be located.'; | |
var MSG_TEXT_DID_NOT_MATCH = DEFAULT_MSG + ' ' + ' Actual text <%s> did not contain <%s>.'; | |
var MSG_HREF_DID_NOT_MATCH = DEFAULT_MSG + ' ' + ' Actual href <%s> did not end with <%s>.'; | |
this.message = msg || util.format(DEFAULT_MSG, selector, text, href); | |
function endsWith(string, suffix) { | |
return string.indexOf(suffix, string.length - suffix.length) !== -1; | |
} | |
this.expected = function() { | |
return { | |
href: href, | |
text: text | |
}; | |
}; | |
this.pass = function(value) { | |
// suffix check for link matching | |
return endsWith(value.href, href) && value.text.indexOf(text) > -1; | |
}; | |
this.failure = function(result) { | |
var failed = (typeof result.href !== 'string' || | |
typeof result.text !== 'string'); | |
if (failed) { | |
var defaultMsg = MSG_ELEMENT_NOT_FOUND; | |
this.message = msg || util.format( | |
MSG_ELEMENT_NOT_FOUND, | |
selector, | |
text, | |
href | |
); | |
return true; | |
} | |
if (!endsWith(result.href, href)) { | |
this.message = msg || util.format( | |
MSG_HREF_DID_NOT_MATCH, | |
selector, | |
text, | |
href, | |
result.href, | |
href | |
); | |
return true; | |
} | |
if (result.text.indexOf(text) <= -1) { | |
this.message = msg || util.format( | |
MSG_TEXT_DID_NOT_MATCH, | |
selector, | |
text, | |
href, | |
result.text, | |
text | |
); | |
return true; | |
} | |
return failed; | |
}; | |
this.value = function(result) { | |
return result; | |
}; | |
this.command = function(callback) { | |
return this.api.getAttribute(selector, 'href', function(hrefResult) { | |
return this.api.getText(selector, function(textResult) { | |
callback({ | |
href: hrefResult.value, | |
text: textResult.value | |
}); | |
}.bind(this)); | |
}.bind(this)); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment