images.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import fs from 'fs';
  2. import { PNG } from 'pngjs';
  3. import { Page } from 'puppeteer-core';
  4. import pixelmatch from 'pixelmatch';
  5. import { constants } from './constants';
  6. export const takeScreenShot = async (page: Page, fileName: string) => {
  7. const outputFolderExists = fs.existsSync(constants.screenShotsOutputDir);
  8. if (!outputFolderExists) {
  9. fs.mkdirSync(constants.screenShotsOutputDir);
  10. }
  11. const path = `${constants.screenShotsOutputDir}/${fileName}.png`;
  12. await page.screenshot({ path, type: 'png', fullPage: false });
  13. };
  14. export const compareScreenShots = async (fileName: string) =>
  15. new Promise(resolve => {
  16. let filesRead = 0;
  17. const doneReading = () => {
  18. if (++filesRead < 2) {
  19. return;
  20. }
  21. expect(screenShotFromTest.width).toEqual(screenShotFromTruth.width);
  22. expect(screenShotFromTest.height).toEqual(screenShotFromTruth.height);
  23. const diff = new PNG({ width: screenShotFromTest.width, height: screenShotFromTruth.height });
  24. const numDiffPixels = pixelmatch(
  25. screenShotFromTest.data,
  26. screenShotFromTruth.data,
  27. diff.data,
  28. screenShotFromTest.width,
  29. screenShotFromTest.height,
  30. { threshold: 0.1 }
  31. );
  32. expect(numDiffPixels).toBe(0);
  33. resolve();
  34. };
  35. const screenShotFromTest = fs
  36. .createReadStream(`${constants.screenShotsOutputDir}/${fileName}.png`)
  37. .pipe(new PNG())
  38. .on('parsed', doneReading);
  39. const screenShotFromTruth = fs
  40. .createReadStream(`${constants.screenShotsTruthDir}/${fileName}.png`)
  41. .pipe(new PNG())
  42. .on('parsed', doneReading);
  43. });