Skip to content

Commit

Permalink
chore(e2e): code refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
fshovchko committed Sep 11, 2024
1 parent 40b19ec commit 43d4fb6
Show file tree
Hide file tree
Showing 21 changed files with 145 additions and 132 deletions.
2 changes: 1 addition & 1 deletion e2e/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ module.exports = {
roots: ['./tests/'],
testRegex: ['(.+)\\.(spec|test)\\.ts$', '(.+).feature'],
moduleFileExtensions: ['ts', 'js', 'feature'],
setupFilesAfterEnv: ['./setup/serializers/image.ts', './setup/scenarios.ts'],
setupFilesAfterEnv: ['./setup/serializers/image-snapshot.ts', './setup/scenarios.ts'],
reporters: [
['./reporters/reporter.js', {
diffDir: './.diff',
Expand Down
2 changes: 1 addition & 1 deletion e2e/reporters/printers.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ function printFiles(fileStat, basePath) {
text += `<tr><td>${test.name}:${test.title}</td><td>${statusTest}</td><td>${timeStr}</td></tr>\n`;

if (test.status !== 'passed' && test.hasSnapshot) {
text += `<tr><td colspan="3"><img src="${resolveURL(basePath, test.snapshot)}" alt="Test Diff ${test.snapshot}"/></td></tr>`;
text += `<tr><td colspan="3"><img src="${resolveURL(basePath, `${test.dirPath}/${test.snapshot}`)}" alt="Test Diff ${test.snapshot}"/></td></tr>`;
}
if (test.status !== 'passed' && !test.hasSnapshot) {
text += `<tr><td colspan="3">\n`;
Expand Down
23 changes: 9 additions & 14 deletions e2e/reporters/reporter.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,12 @@ const fs = require('fs');
const path = require('path');

const {print} = require('./printers');

const sanitize = (str) => (str || '').replace(/\W+/g, '-').toLowerCase();
const {buildSnapshotName, getDiffDir, getDirName} = require('../utils/image-snapshot.name');
const {mkDir} = require('../utils/directory');

const writeFileSafe = (filename, data) => {
const dirname = path.dirname(filename);
if (!fs.existsSync(dirname)) {
fs.mkdirSync(dirname, {recursive: true});
}
mkDir(dirname)
fs.writeFileSync(filename, data);
};

Expand Down Expand Up @@ -44,20 +42,17 @@ class SnapshotAwareReporter {
}

buildTestStat(test, testPath) {
const {ancestorTitles, status, title, duration} = test;
const {status, title, duration, fullName} = test;
const filename = path.basename(testPath);
const name = ancestorTitles.join(' > ');
const statBase = {name, filename, status, title, time: duration};
const statBase = {status, filename, title, time: duration};
if (status === 'passed') return statBase;

const snapshotParts = [filename, ...ancestorTitles, title, 'diff'];
const snapshotName = snapshotParts.map(sanitize).join('-') + '.jpg';
const snapshotPath = path.join(this._options.diffDir, snapshotName);
const snapshotExists = fs.existsSync(snapshotPath);
const snapshotName = buildSnapshotName(fullName, 'diff');
const snapshotExists = fs.existsSync(path.join(getDiffDir(testPath), snapshotName));
return Object.assign(statBase, {
message: test.failureMessages[0],
messages: test.failureMessages,
hasSnapshot: snapshotExists,
dirPath: getDirName(testPath),
snapshot: snapshotExists ? snapshotName : null
});
}
Expand All @@ -67,7 +62,7 @@ class SnapshotAwareReporter {
const basePath = path.resolve(this._globalConfig.rootDir);
for (const result of results.testResults) {
const filepath = path.relative(basePath, result.testFilePath);
const tests = result.testResults.map(test => this.buildTestStat(test, filepath));
const tests = result.testResults.map(test => this.buildTestStat(test, result.testFilePath));
testResults.push({filepath, tests});
}
return testResults;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import pixelmatch from 'pixelmatch';
import {SnapshotDataProcessor} from './image-processor';
import {SnapshotDataProcessor} from './image-snapshot.pocessor';

import type {SnapshotData} from './image-processor';
import type {SnapshotData} from './image-snapshot.pocessor';

export type SnapshotMatcherOptions = pixelmatch.PixelmatchOptions;

Expand Down Expand Up @@ -49,7 +49,7 @@ export class SnapshotMatcher {
try {
const numDiffPixel = pixelmatch(prevImg.data, currImg.data, diffBuffer, width, height, this.config);
if (numDiffPixel > width * height * SnapshotMatcher.MIN_DIFF_THRESHOLD) {
return {reason: 'content', path: await SnapshotDataProcessor.saveDiff(this.received, diffBuffer)};
return {reason: 'content', path: await SnapshotDataProcessor.saveDiffImage(this.received, diffBuffer)};
}
} catch (e) {
return {reason: 'error'};
Expand Down
79 changes: 79 additions & 0 deletions e2e/setup/serializers/image-snapshot.pocessor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import path from 'path';
import fs from 'fs';
import sharp from 'sharp';

import {mkDir} from '../../utils/directory';
import {getDiffDir, getSnapshotDir, buildSnapshotName} from '../../utils/image-snapshot.name';
import {SharpService} from './image-snapshot.sharp';

import type {SharpContext} from './image-snapshot.sharp';

export interface SnapshotData {
snapshotPath: string;
diffPath: string;
diffDir: string;

current: {
img: sharp.Sharp;
buffer: SharpContext;
};

previous: {
buffer: SharpContext | undefined;
};
}

export class SnapshotDataProcessor {
public static async process(context: jest.MatcherContext, received: Buffer): Promise<SnapshotData> {
const {testPath, currentTestName} = context;

const snapshotDir = getSnapshotDir(testPath!);
const diffDir = getDiffDir(testPath!);
mkDir(snapshotDir);

const snapshotPath = path.join(snapshotDir, buildSnapshotName(currentTestName!));
const diffPath = path.join(diffDir, buildSnapshotName(currentTestName!, 'diff'));

const shouldUpdate = !fs.existsSync(snapshotPath) || context.snapshotState._updateSnapshot === 'all';
const recievedJPG = SharpService.toJPEG(received);
return {
diffPath,
snapshotPath,
diffDir,

current: {
img: recievedJPG,
buffer: await (SharpService.toRawBuffered(await recievedJPG.toBuffer()))
},

previous: {
buffer: shouldUpdate ? undefined : await (SharpService.toRawBuffered(snapshotPath))
}
};
}

public static async saveDiffImage(data: SnapshotData, diffBuffer: Buffer): Promise<string | undefined> {
const {current, previous, diffDir, diffPath} = data;
const {width, height} = previous.buffer!.info;
mkDir(diffDir);

const rawOptions = {raw: {width, height, channels: 4}};
await sharp({
create: {
width: width * 3,
height,
channels: 4,
background: {r: 0, g: 0, b: 0, alpha: 0}
}
})
.composite([
{input: await SharpService.toJPEGBufferd(previous.buffer!.data, rawOptions), left: 0, top: 0},
{input: await SharpService.toJPEGBufferd(diffBuffer, rawOptions), left: width, top: 0},
{input: await SharpService.toJPEGBufferd(current.buffer.data, rawOptions), left: width * 2, top: 0}
])
.jpeg()
.toFile(diffPath);

return diffPath;
}
}
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {SnapshotDataProcessor} from './image/image-processor';
import {SnapshotMatcher} from './image/snapshot-matcher';
import type {SnapshotMatcherOptions} from './image/snapshot-matcher';
import {SnapshotDataProcessor} from './image-snapshot.pocessor';
import {SnapshotMatcher} from './image-snapshot.matcher';
import type {SnapshotMatcherOptions} from './image-snapshot.matcher';

expect.extend({async toMatchImageSnapshot(received: Buffer, options: SnapshotMatcherOptions = {}) {
const imageList = await SnapshotDataProcessor.process(this, received);
Expand Down
42 changes: 0 additions & 42 deletions e2e/setup/serializers/image/diff-builder.ts

This file was deleted.

60 changes: 0 additions & 60 deletions e2e/setup/serializers/image/image-processor.ts

This file was deleted.

5 changes: 0 additions & 5 deletions e2e/setup/serializers/image/utils/directory.ts

This file was deleted.

3 changes: 0 additions & 3 deletions e2e/setup/serializers/image/utils/name.ts

This file was deleted.

1 change: 1 addition & 0 deletions e2e/utils/directory.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export declare function mkDir(dirPath: string): void;
9 changes: 9 additions & 0 deletions e2e/utils/directory.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const fs = require('fs');

function mkDir(dirPath) {
if (!fs.existsSync(dirPath)) fs.mkdirSync(dirPath, {recursive: true});
}

module.exports = {
mkDir
};
7 changes: 7 additions & 0 deletions e2e/utils/image-snapshot.name.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export declare function buildSnapshotName(...snapshotParts: string[]): string;

export declare function getSnapshotDir(testPath: string): string;

export declare function getDiffDir(testPath: string): string;

export declare function getDirName(testPath: string): string;
32 changes: 32 additions & 0 deletions e2e/utils/image-snapshot.name.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
const path = require('path');
const jestConfig = require(path.resolve(process.cwd(), 'jest.config.js'));

function buildSnapshotName(...snapshotParts) {
const sanitize = (str) => (str || '').replace(/\W+/g, '-').toLowerCase();
return snapshotParts.map(sanitize).join('-') + '.jpg';
}

const getRootDir = (testPath) => jestConfig.roots.find((root) => path.resolve(testPath).includes(path.resolve(root)));

function getDirName(testPath) {
const rootDir = getRootDir(testPath);
const basePath = path.resolve(rootDir);
return path.relative(basePath, testPath)
}

function getSnapshotDir(testPath) {
const snapshotDir = path.resolve(getRootDir(testPath), '__image_snapshots__');
return path.join(snapshotDir, getDirName(testPath));
}

function getDiffDir(testPath) {
const diffDir = path.resolve('.diff');
return path.join(diffDir, getDirName(testPath));
}

module.exports = {
buildSnapshotName,
getSnapshotDir,
getDiffDir,
getDirName
};

0 comments on commit 43d4fb6

Please sign in to comment.