to-have-display-value.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.toHaveDisplayValue = toHaveDisplayValue;
  6. var _utils = require("./utils");
  7. function toHaveDisplayValue(htmlElement, expectedValue) {
  8. (0, _utils.checkHtmlElement)(htmlElement, toHaveDisplayValue, this);
  9. const tagName = htmlElement.tagName.toLowerCase();
  10. if (!['select', 'input', 'textarea'].includes(tagName)) {
  11. throw new Error('.toHaveDisplayValue() currently supports only input, textarea or select elements, try with another matcher instead.');
  12. }
  13. if (tagName === 'input' && ['radio', 'checkbox'].includes(htmlElement.type)) {
  14. throw new Error(`.toHaveDisplayValue() currently does not support input[type="${htmlElement.type}"], try with another matcher instead.`);
  15. }
  16. const values = getValues(tagName, htmlElement);
  17. const expectedValues = getExpectedValues(expectedValue);
  18. const numberOfMatchesWithValues = expectedValues.filter(expected => values.some(value => expected instanceof RegExp ? expected.test(value) : this.equals(value, String(expected)))).length;
  19. const matchedWithAllValues = numberOfMatchesWithValues === values.length;
  20. const matchedWithAllExpectedValues = numberOfMatchesWithValues === expectedValues.length;
  21. return {
  22. pass: matchedWithAllValues && matchedWithAllExpectedValues,
  23. message: () => (0, _utils.getMessage)(this, this.utils.matcherHint(`${this.isNot ? '.not' : ''}.toHaveDisplayValue`, 'element', ''), `Expected element ${this.isNot ? 'not ' : ''}to have display value`, expectedValue, 'Received', values)
  24. };
  25. }
  26. function getValues(tagName, htmlElement) {
  27. return tagName === 'select' ? Array.from(htmlElement).filter(option => option.selected).map(option => option.textContent) : [htmlElement.value];
  28. }
  29. function getExpectedValues(expectedValue) {
  30. return expectedValue instanceof Array ? expectedValue : [expectedValue];
  31. }