Welcome to mirror list, hosted at ThFree Co, Russian Federation.

matchers.js « javascripts « spec - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: ae005e152edd348e4a52f4461c97b96ef8700e98 (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
37
38
39
40
41
42
import pixelmatch from 'pixelmatch';

export default {
  toImageDiffEqual: () => {
    const getImageData = (img) => {
      const canvas = document.createElement('canvas');
      canvas.width = img.width;
      canvas.height = img.height;
      canvas.getContext('2d').drawImage(img, 0, 0);
      return canvas.getContext('2d').getImageData(0, 0, img.width, img.height).data;
    };

    return {
      compare(actual, expected, threshold = 0.1) {
        if (actual.height !== expected.height || actual.width !== expected.width) {
          return {
            pass: false,
            message: `Expected image dimensions (h x w) of ${expected.height}x${expected.width}.
            Received an image with ${actual.height}x${actual.width}`,
          };
        }

        const { width, height } = actual;
        const differentPixels = pixelmatch(
          getImageData(actual),
          getImageData(expected),
          null,
          width,
          height,
          { threshold },
        );

        return {
          pass: differentPixels < 20,
          message: `${differentPixels} pixels differ more than ${
            threshold * 100
          } percent between input and output.`,
        };
      },
    };
  },
};