matchers.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. 'use strict';
  2. import Chart from 'chart.js';
  3. import pixelmatch from 'pixelmatch';
  4. import utils from './utils';
  5. function toPercent(value) {
  6. return Math.round(value * 10000) / 100;
  7. }
  8. function buildPixelMatchPreview(actual, expected, diff, threshold, tolerance, count) {
  9. var ratio = count / (actual.width * actual.height);
  10. var wrapper = document.createElement('div');
  11. wrapper.style.cssText = 'display: flex; overflow-y: auto';
  12. [
  13. {data: actual, label: 'Actual'},
  14. {data: expected, label: 'Expected'},
  15. {data: diff, label:
  16. 'diff: ' + count + 'px ' +
  17. '(' + toPercent(ratio) + '%)<br/>' +
  18. 'thr: ' + toPercent(threshold) + '%, ' +
  19. 'tol: ' + toPercent(tolerance) + '%'
  20. }
  21. ].forEach(function(values) {
  22. var item = document.createElement('div');
  23. item.style.cssText = 'text-align: center; font: 12px monospace; line-height: 1.4; margin: 8px';
  24. item.innerHTML = '<div style="margin: 8px; height: 32px">' + values.label + '</div>';
  25. item.appendChild(utils.canvasFromImageData(values.data));
  26. wrapper.appendChild(item);
  27. });
  28. // WORKAROUND: https://github.com/karma-runner/karma-jasmine/issues/139
  29. wrapper.indexOf = function() {
  30. return -1;
  31. };
  32. return wrapper;
  33. }
  34. function toEqualImageData() {
  35. return {
  36. compare: function(actual, expected, opts) {
  37. var message = null;
  38. var debug = opts.debug || false;
  39. var tolerance = opts.tolerance === undefined ? 0.001 : opts.tolerance;
  40. var threshold = opts.threshold === undefined ? 0.1 : opts.threshold;
  41. var ctx, idata, ddata, w, h, count, ratio;
  42. if (actual instanceof Chart) {
  43. ctx = actual.ctx;
  44. } else if (actual instanceof HTMLCanvasElement) {
  45. ctx = actual.getContext('2d');
  46. } else if (actual instanceof CanvasRenderingContext2D) {
  47. ctx = actual;
  48. }
  49. if (ctx) {
  50. h = expected.height;
  51. w = expected.width;
  52. idata = ctx.getImageData(0, 0, w, h);
  53. ddata = utils.createImageData(w, h);
  54. count = pixelmatch(idata.data, expected.data, ddata.data, w, h, {threshold: threshold});
  55. ratio = count / (w * h);
  56. if ((ratio > tolerance) || debug) {
  57. message = buildPixelMatchPreview(idata, expected, ddata, threshold, tolerance, count);
  58. }
  59. } else {
  60. message = 'Input value is not a valid image source.';
  61. }
  62. return {
  63. message: message,
  64. pass: !message
  65. };
  66. }
  67. };
  68. }
  69. export default {
  70. toEqualImageData: toEqualImageData
  71. };