to-have-class.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.toHaveClass = toHaveClass;
  6. var _utils = require("./utils");
  7. function getExpectedClassNamesAndOptions(params) {
  8. const lastParam = params.pop();
  9. let expectedClassNames, options;
  10. if (typeof lastParam === 'object') {
  11. expectedClassNames = params;
  12. options = lastParam;
  13. } else {
  14. expectedClassNames = params.concat(lastParam);
  15. options = {
  16. exact: false
  17. };
  18. }
  19. return {
  20. expectedClassNames,
  21. options
  22. };
  23. }
  24. function splitClassNames(str) {
  25. if (!str) {
  26. return [];
  27. }
  28. return str.split(/\s+/).filter(s => s.length > 0);
  29. }
  30. function isSubset(subset, superset) {
  31. return subset.every(item => superset.includes(item));
  32. }
  33. function toHaveClass(htmlElement, ...params) {
  34. (0, _utils.checkHtmlElement)(htmlElement, toHaveClass, this);
  35. const {
  36. expectedClassNames,
  37. options
  38. } = getExpectedClassNamesAndOptions(params);
  39. const received = splitClassNames(htmlElement.getAttribute('class'));
  40. const expected = expectedClassNames.reduce((acc, className) => acc.concat(splitClassNames(className)), []);
  41. if (options.exact) {
  42. return {
  43. pass: isSubset(expected, received) && expected.length === received.length,
  44. message: () => {
  45. const to = this.isNot ? 'not to' : 'to';
  46. return (0, _utils.getMessage)(this, `Expected the element ${to} have EXACTLY defined classes`, expected.join(' '), 'Received', received.join(' '));
  47. }
  48. };
  49. }
  50. return expected.length > 0 ? {
  51. pass: isSubset(expected, received),
  52. message: () => {
  53. const to = this.isNot ? 'not to' : 'to';
  54. return (0, _utils.getMessage)(this, this.utils.matcherHint(`${this.isNot ? '.not' : ''}.toHaveClass`, 'element', this.utils.printExpected(expected.join(' '))), `Expected the element ${to} have class`, expected.join(' '), 'Received', received.join(' '));
  55. }
  56. } : {
  57. pass: this.isNot ? received.length > 0 : false,
  58. message: () => this.isNot ? (0, _utils.getMessage)(this, this.utils.matcherHint('.not.toHaveClass', 'element', ''), 'Expected the element to have classes', '(none)', 'Received', received.join(' ')) : [this.utils.matcherHint(`.toHaveClass`, 'element'), 'At least one expected class must be provided.'].join('\n')
  59. };
  60. }