to-be-required.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.toBeRequired = toBeRequired;
  6. var _utils = require("./utils");
  7. // form elements that support 'required'
  8. const FORM_TAGS = ['select', 'textarea'];
  9. const ARIA_FORM_TAGS = ['input', 'select', 'textarea'];
  10. const UNSUPPORTED_INPUT_TYPES = ['color', 'hidden', 'range', 'submit', 'image', 'reset'];
  11. const SUPPORTED_ARIA_ROLES = ['combobox', 'gridcell', 'radiogroup', 'spinbutton', 'tree'];
  12. function isRequiredOnFormTagsExceptInput(element) {
  13. return FORM_TAGS.includes((0, _utils.getTag)(element)) && element.hasAttribute('required');
  14. }
  15. function isRequiredOnSupportedInput(element) {
  16. return (0, _utils.getTag)(element) === 'input' && element.hasAttribute('required') && (element.hasAttribute('type') && !UNSUPPORTED_INPUT_TYPES.includes(element.getAttribute('type')) || !element.hasAttribute('type'));
  17. }
  18. function isElementRequiredByARIA(element) {
  19. return element.hasAttribute('aria-required') && element.getAttribute('aria-required') === 'true' && (ARIA_FORM_TAGS.includes((0, _utils.getTag)(element)) || element.hasAttribute('role') && SUPPORTED_ARIA_ROLES.includes(element.getAttribute('role')));
  20. }
  21. function toBeRequired(element) {
  22. (0, _utils.checkHtmlElement)(element, toBeRequired, this);
  23. const isRequired = isRequiredOnFormTagsExceptInput(element) || isRequiredOnSupportedInput(element) || isElementRequiredByARIA(element);
  24. return {
  25. pass: isRequired,
  26. message: () => {
  27. const is = isRequired ? 'is' : 'is not';
  28. return [this.utils.matcherHint(`${this.isNot ? '.not' : ''}.toBeRequired`, 'element', ''), '', `Received element ${is} required:`, ` ${this.utils.printReceived(element.cloneNode(false))}`].join('\n');
  29. }
  30. };
  31. }