to-have-errormessage.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.toHaveErrorMessage = toHaveErrorMessage;
  6. var _utils = require("./utils");
  7. // See aria-errormessage spec https://www.w3.org/TR/wai-aria-1.2/#aria-errormessage
  8. function toHaveErrorMessage(htmlElement, checkWith) {
  9. (0, _utils.checkHtmlElement)(htmlElement, toHaveErrorMessage, this);
  10. if (!htmlElement.hasAttribute('aria-invalid') || htmlElement.getAttribute('aria-invalid') === 'false') {
  11. const not = this.isNot ? '.not' : '';
  12. return {
  13. pass: false,
  14. message: () => {
  15. return (0, _utils.getMessage)(this, this.utils.matcherHint(`${not}.toHaveErrorMessage`, 'element', ''), `Expected the element to have invalid state indicated by`, 'aria-invalid="true"', 'Received', htmlElement.hasAttribute('aria-invalid') ? `aria-invalid="${htmlElement.getAttribute('aria-invalid')}"` : this.utils.printReceived(''));
  16. }
  17. };
  18. }
  19. const expectsErrorMessage = checkWith !== undefined;
  20. const errormessageIDRaw = htmlElement.getAttribute('aria-errormessage') || '';
  21. const errormessageIDs = errormessageIDRaw.split(/\s+/).filter(Boolean);
  22. let errormessage = '';
  23. if (errormessageIDs.length > 0) {
  24. const document = htmlElement.ownerDocument;
  25. const errormessageEls = errormessageIDs.map(errormessageID => document.getElementById(errormessageID)).filter(Boolean);
  26. errormessage = (0, _utils.normalize)(errormessageEls.map(el => el.textContent).join(' '));
  27. }
  28. return {
  29. pass: expectsErrorMessage ? checkWith instanceof RegExp ? checkWith.test(errormessage) : this.equals(errormessage, checkWith) : Boolean(errormessage),
  30. message: () => {
  31. const to = this.isNot ? 'not to' : 'to';
  32. return (0, _utils.getMessage)(this, this.utils.matcherHint(`${this.isNot ? '.not' : ''}.toHaveErrorMessage`, 'element', ''), `Expected the element ${to} have error message`, this.utils.printExpected(checkWith), 'Received', this.utils.printReceived(errormessage));
  33. }
  34. };
  35. }