summaryrefslogtreecommitdiff
path: root/spec/frontend/__helpers__/matchers/to_have_sprite_icon.js
blob: bce9d93bea86f33d77f644544de8a72fdaa0f3f2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
export const toHaveSpriteIcon = (element, iconName) => {
  if (!iconName) {
    throw new Error('toHaveSpriteIcon is missing iconName argument!');
  }

  if (!(element instanceof HTMLElement)) {
    throw new Error(`${element} is not a DOM element!`);
  }

  const iconReferences = [].slice.apply(element.querySelectorAll('svg use'));
  const matchingIcon = iconReferences.find(
    (reference) => reference.parentNode.getAttribute('data-testid') === `${iconName}-icon`,
  );

  const pass = Boolean(matchingIcon);

  let message;
  if (pass) {
    message = `${element.outerHTML} contains the sprite icon "${iconName}"!`;
  } else {
    message = `${element.outerHTML} does not contain the sprite icon "${iconName}"!`;

    const existingIcons = iconReferences.map((reference) => {
      const iconUrl = reference.getAttribute('href');
      return `"${iconUrl.replace(/^.+#/, '')}"`;
    });
    if (existingIcons.length > 0) {
      message += ` (only found ${existingIcons.join(',')})`;
    }
  }

  return {
    pass,
    message: () => message,
  };
};