attributeEquals.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /**
  2. * Checks if the given attribute of an element has the expected value.
  3. *
  4. * ```
  5. * this.demoTest = function (client) {
  6. * browser.assert.attributeEquals('body', 'data-attr', 'some value');
  7. * };
  8. * ```
  9. *
  10. * @method attributeEquals
  11. * @param {string} selector The selector (CSS / Xpath) used to locate the element.
  12. * @param {string} attribute The attribute name
  13. * @param {string} expected The expected value of the attribute to check.
  14. * @param {string} [message] Optional log message to display in the output. If missing, one is displayed by default.
  15. * @api assertions
  16. */
  17. var util = require('util');
  18. exports.assertion = function(selector, attribute, expected, msg) {
  19. var DEFAULT_MSG = 'Testing if attribute %s of <%s> equals "%s".';
  20. var MSG_ELEMENT_NOT_FOUND = DEFAULT_MSG + ' ' + 'Element could not be located.';
  21. var MSG_ATTR_NOT_FOUND = DEFAULT_MSG + ' ' + 'Element does not have a ' + attribute + ' attribute.';
  22. this.message = msg || util.format(DEFAULT_MSG, attribute, selector, expected);
  23. this.expected = function() {
  24. return expected;
  25. };
  26. this.pass = function(value) {
  27. return value === expected;
  28. };
  29. this.failure = function(result) {
  30. var failed = (result === false) ||
  31. // no such element
  32. result && (result.status === -1 || result.value === null);
  33. if (failed) {
  34. var defaultMsg = MSG_ELEMENT_NOT_FOUND;
  35. if (result && result.value === null) {
  36. defaultMsg = MSG_ATTR_NOT_FOUND;
  37. }
  38. this.message = msg || util.format(defaultMsg, attribute, selector, expected);
  39. }
  40. return failed;
  41. };
  42. this.value = function(result) {
  43. return result.value;
  44. };
  45. this.command = function(callback) {
  46. return this.api.getAttribute(selector, attribute, callback);
  47. };
  48. };