How to use snapshotPath method in differencify

Best JavaScript code snippet using differencify

snapshotPlugin.ts

Source:snapshotPlugin.ts Github

copy

Full Screen

1/* eslint-disable @typescript-eslint/no-empty-function */2import { TestRunnerPlugin } from '@web/test-runner-core';3import { ServerStartParams } from '@web/dev-server-core';4import path from 'path';5import fs from 'fs';6import { promisify } from 'util';7import mkdirp from 'mkdirp';8const readFile = promisify(fs.readFile);9const writeFile = promisify(fs.writeFile);10const unlink = promisify(fs.unlink);11const access = promisify(fs.access);12async function fileExists(filePath: string) {13 try {14 await access(filePath);15 return true;16 } catch {17 return false;18 }19}20function isObject(payload: unknown): payload is Record<string, unknown> {21 return payload != null && typeof payload === 'object';22}23export interface SaveSnapshotPayload {24 name: string;25 content: string;26}27function isSaveSnapshotPayload(payload: unknown): payload is SaveSnapshotPayload {28 if (!isObject(payload)) throw new Error('You must provide a payload object');29 if (typeof payload.name !== 'string') throw new Error('You must provide a path option');30 if (payload.content !== undefined && typeof payload.content !== 'string')31 throw new Error('You must provide a content option');32 return true;33}34function getSnapshotPath(testFile: string) {35 const testDir = path.dirname(testFile);36 const testFileName = path.basename(testFile);37 const ext = path.extname(testFileName);38 const fileWithoutExt = testFileName.substring(0, testFileName.length - ext.length);39 return path.join(testDir, '__snapshots__', `${fileWithoutExt}.snap.js`);40}41class SnapshotStore {42 private snapshots = new Map<string, string>();43 private sessionToSnapshotPath = new Map<string, string>();44 private readOperations = new Map<string, { promise: Promise<void>; resolve: () => void }>();45 async get(testFilePath: string): Promise<string> {46 const snapshotPath = getSnapshotPath(testFilePath);47 if (this.readOperations.has(snapshotPath)) {48 // something else is already reading, wait for it49 await this.readOperations.get(snapshotPath)?.promise;50 }51 const cachedContent = this.snapshots.get(snapshotPath);52 if (cachedContent) {53 // return from cache54 return cachedContent;55 }56 const promiseObj = { resolve: () => {}, promise: Promise.resolve() };57 promiseObj.promise = new Promise<void>(resolve => {58 promiseObj.resolve = resolve;59 });60 this.readOperations.set(testFilePath, promiseObj);61 // store in cache62 const content = (await fileExists(snapshotPath))63 ? await readFile(snapshotPath, 'utf-8')64 : '/* @web/test-runner snapshot v1 */\nexport const snapshots = {};\n\n';65 this.snapshots.set(snapshotPath, content);66 // resolve read promise to let others who are waiting continue67 this.readOperations.get(snapshotPath)?.resolve();68 this.readOperations.delete(snapshotPath);69 return content;70 }71 async saveSnapshot(72 sessionId: string,73 testFilePath: string,74 name: string,75 updatedSnapshot: string,76 ) {77 const snapshotPath = getSnapshotPath(testFilePath);78 const nameStr = JSON.stringify(name);79 const startMarker = `snapshots[${nameStr}]`;80 const endMarker = `/* end snapshot ${name} */\n\n`;81 const replacement = updatedSnapshot82 ? `${startMarker} = \n\`${updatedSnapshot}\`;\n${endMarker}`83 : '';84 const content = await this.get(testFilePath);85 let updatedContent: string;86 const startIndex = content.indexOf(startMarker);87 if (startIndex !== -1) {88 // replace existing snapshot89 const endIndex = content.indexOf(endMarker);90 if (endIndex === -1) {91 throw new Error('Missing snapshot end marker');92 }93 const beforeReplace = content.substring(0, startIndex);94 const afterReplace = content.substring(endIndex + endMarker.length);95 updatedContent = `${beforeReplace}${replacement}${afterReplace}`;96 } else {97 // add new snapshot98 updatedContent = `${content}${replacement}`;99 }100 if (updatedContent === content) {101 // snapshot did not actually change, avoid marking snapshot as dirty102 return;103 }104 this.sessionToSnapshotPath.set(sessionId, snapshotPath);105 this.snapshots.set(snapshotPath, updatedContent);106 }107 getSnapshotPathForSession(sessionId: string) {108 return this.sessionToSnapshotPath.get(sessionId);109 }110 async writeSnapshot(snapshotPath: string) {111 const updatedContent = this.snapshots.get(snapshotPath);112 if (!updatedContent) {113 throw new Error('Unexpected error while writing snapshots, could not find snapshot content.');114 }115 if (updatedContent.includes('/* end snapshot')) {116 // update or create snapshot117 const fileDir = path.dirname(snapshotPath);118 await mkdirp(fileDir);119 await writeFile(snapshotPath, updatedContent);120 } else {121 // snapshot file is empty, remove it122 if (await fileExists(snapshotPath)) {123 await unlink(snapshotPath);124 }125 }126 }127}128export interface SnapshotPluginConfig {129 updateSnapshots?: boolean;130}131export function snapshotPlugin(config?: SnapshotPluginConfig): TestRunnerPlugin {132 const updateSnapshots = config && config.updateSnapshots;133 const snapshots = new SnapshotStore();134 const writePromises = new Set<Promise<void>>();135 return {136 name: 'file-commands',137 serverStart({ webSockets }: ServerStartParams) {138 webSockets!.on('message', async ({ data }) => {139 const { type, sessionId } = data;140 if (type === 'wtr-session-finished') {141 if (typeof sessionId !== 'string') {142 throw new Error('Missing session id in wtr-session-finished event');143 }144 const snapshotPath = snapshots.getSnapshotPathForSession(sessionId);145 if (!snapshotPath) {146 return;147 }148 const writePromise = snapshots.writeSnapshot(snapshotPath);149 writePromises.add(writePromise);150 await writePromise;151 writePromises.delete(writePromise);152 }153 });154 },155 async serverStop() {156 // ensure all write operations are finished157 await Promise.all([...writePromises]);158 },159 async executeCommand({ command, payload, session }) {160 if (command === 'get-snapshot-config') {161 return { updateSnapshots };162 }163 if (command === 'get-snapshots') {164 const content = await snapshots.get(session.testFile);165 return { content };166 }167 if (command === 'save-snapshot') {168 if (!isSaveSnapshotPayload(payload)) {169 throw new Error('Invalid save snapshot payload');170 }171 await snapshots.saveSnapshot(session.id, session.testFile, payload.name, payload.content);172 return true;173 }174 },175 };...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1let cp = require("child_process");2let fs = require("fs");3let path = require("path");4class NodeOomHeapDumpImpl {5 constructor(options) {6 this._opts = options;7 this._files = [];8 this._busy = false;9 this._count = 0;10 if (this._opts.heapdumpOnOOM) {11 if (options.OOMImplementation === "NATIVE_HOOK") {12 require('bindings')('node_oom_heapdump_native.node').call(this._getHeapSnapshotPath(this._opts.path), this._opts.addTimestamp);13 }14 }15 }16 /**17 * Calls the designated worker and returns a promise18 * @param {String} workerPath - path of the worker19 * @param {String[]} workerArgs - arguments to worker20 * @return {Promise} resolve on success, reject on error21 */22 _callWorker(workerPath, workerArgs) {23 if (this._busy) {24 return new Promise((resolve, reject) => {25 reject(new Error("A CPU profile or heapdump is already being created, please retry later."));26 });27 }28 var args = [path.resolve(__dirname, workerPath)].concat(workerArgs);29 // use 'require-main-filename' module instead of require.main.filename, see https://github.com/blueconic/node-oom-heapdump/issues/330 let mainFilename = require('require-main-filename')();31 // start worker32 let child = cp.spawn('node', args, {33 cmd: path.dirname(mainFilename),34 stdio: 'inherit'35 });36 return new Promise((resolve, reject) => {37 this._busy = true;38 var error = null;39 child.on('error', (err) => {40 error = err;41 reject(err);42 });43 child.on('exit', (code) => {44 if (!error) {45 if (code === 0) {46 resolve();47 } else {48 reject(new Error("Worker exited with statusCode: " + code));49 }50 }51 this._busy = false;52 });53 });54 }55 /**56 * Returns the path to the created heap snapshot in a promise, or rejects on error57 * @param {String} snapshotPath - path of the snapshot58 * @param {String} logPrefix - optional log prefix message when heapdump is created59 * @return {Promise} the heap snapshot path on success or error on rejection60 */61 createHeapSnapshot(snapshotPath, logPrefix) {62 snapshotPath = this._getHeapSnapshotPath(snapshotPath, logPrefix);63 // start OoMworker to create heapdump64 return this._callWorker('./heapdumpWorker.js', [this._opts.port, snapshotPath, logPrefix || ""]).then(() => {65 if (logPrefix === "OoM") {66 this._count++;67 }68 if (!this._files.includes(snapshotPath)) {69 this._files.push(snapshotPath);70 }71 return snapshotPath;72 });73 }74 /**75 * Returns the path to the created CPU profile in a promise, or rejects on error76 * @param {String} cpuProfilePath - path of the CPU profile77 * @param {number} duration - the duration of the cpu profile (in ms)78 * @return {Promise} the CPU profile path on success or error on rejection79 */80 createCpuProfile(cpuProfilePath, duration) {81 if (!cpuProfilePath) {82 cpuProfilePath = path.resolve(__dirname, "../cpuprofile-" + Date.now());83 }84 if (!cpuProfilePath.endsWith(".cpuprofile")) {85 cpuProfilePath += ".cpuprofile";86 }87 // start OoMworker to create heapdump88 return this._callWorker('./cpuProfileWorker.js', [this._opts.port, cpuProfilePath, duration]).then(() => {89 if (!this._files.includes(cpuProfilePath)) {90 this._files.push(cpuProfilePath);91 }92 return cpuProfilePath;93 });94 }95 /**96 * Delete all created heap snapshots97 */98 deleteAllHeapSnapshots() {99 this._files.forEach((snapshotPath) => {100 if (snapshotPath.endsWith(".heapsnapshot")) {101 this.deleteHeapSnapshot(snapshotPath);102 }103 });104 }105 /**106 * Deletes a particular snapshot from disk107 * @param {String} snapshotPath - path of the heap snapshot to delete108 * @return {Promise}109 */110 deleteHeapSnapshot(snapshotPath) {111 return this._deleteFile(snapshotPath);112 }113 /**114 * Delete all created CPU profiles115 */116 deleteAllCpuProfiles() {117 this._files.forEach((path) => {118 if (path.endsWith(".cpuprofile")) {119 this.deleteCpuProfile(path);120 }121 });122 }123 /**124 * Deletes a particular CPU profile from disk125 * @param {String} cpuProfilePath - path of the CPU profile to delete126 * @return {Promise}127 */128 deleteCpuProfile(cpuProfilePath) {129 return this._deleteFile(cpuProfilePath);130 }131 /**132 * Deletes a given CPU profile or heapsnapshot from disk133 * @param {String} path - path to the file to delete134 * @return {Promise}135 */136 _deleteFile(path) {137 return new Promise((resolve, reject) => {138 if (this._files.includes(path)) {139 fs.unlink(path, (err) => {140 if (err) {141 reject(err);142 } else {143 resolve(path);144 }145 });146 } else {147 reject(new Error("File not found:" + path));148 }149 });150 }151 /**152 * Returns a proper snapshot path, based on the given parameter153 * @param {String} snapshotPath 154 * @param {String} logPrefix155 * @return {String} path156 */157 _getHeapSnapshotPath(snapshotPath, logPrefix) {158 if (!snapshotPath) {159 snapshotPath = path.resolve(__dirname, "../heapsnapshot-" + Date.now());160 }161 if (logPrefix === "OoM" && this._opts.addTimestamp) {162 if (snapshotPath.endsWith(".heapsnapshot")) {163 snapshotPath = snapshotPath.replace(".heapsnapshot", "");164 }165 // in case of OoM error, add timestamp if needed 166 snapshotPath += "-" + Date.now();167 }168 if (!snapshotPath.endsWith(".heapsnapshot")) {169 snapshotPath += ".heapsnapshot";170 }171 return snapshotPath;172 }173}...

Full Screen

Full Screen

snapshotcache.ts

Source:snapshotcache.ts Github

copy

Full Screen

1import * as ts_module from "typescript/lib/tsserverlibrary";2import * as fs from "fs";3import * as nodePath from "path";4import { SnapshotDefinition, parseSnapshotFile } from "./utils";5interface Cache {6 definitions: SnapshotDefinition[];7 lastModifiedTime: number;8}9export interface SnapshotInfo {10 file: string;11 definitions: SnapshotDefinition[];12}13/**14 * Simple snapshot source cache15 */16export class SnapshotResolver {17 private _extensions: string[] = [".snap"];18 private _dir: string = "__snapshots__"19 public constructor(20 private ts: typeof ts_module,21 private cacheMap: Map<string, Cache> = new Map(),22 ) { }23 public set extensions(ext: string[]) {24 this._extensions = ext;25 this.cacheMap.clear();26 }27 public get extensions(): string[] {28 return this._extensions;29 }30 public set dir(d: string) {31 this._dir = d;32 this.cacheMap.clear();33 }34 public get dir(): string {35 return this._dir;36 }37 /**38 * Return snapshot definitions for given snapshot file name.39 * May return definitions from cache if snapshot file hasn't been changed40 *41 * @param testFile42 * @returns43 */44 public getSnapshotForFile(testFile: string): SnapshotInfo | undefined {45 const snapshotPath = this.getAllPossiblePathsForFile(testFile).find(path => fs.existsSync(path));46 // if (!fs.existsSync(path)) {47 // return [];48 // }49 if (!snapshotPath) {50 return;51 }52 try {53 const { mtime } = fs.statSync(snapshotPath);54 const cacheEntry = this.cacheMap.get(snapshotPath);55 if (cacheEntry && cacheEntry.lastModifiedTime === mtime.getTime()) {56 return {57 file: snapshotPath,58 definitions: cacheEntry.definitions,59 };60 }61 const source = fs.readFileSync(snapshotPath, "utf8");62 const newEntry: Cache = {63 lastModifiedTime: mtime.getTime(),64 definitions: parseSnapshotFile(this.ts, snapshotPath, source)65 };66 this.cacheMap.set(snapshotPath, newEntry);67 return {68 file: snapshotPath,69 definitions: newEntry.definitions,70 };71 } catch {72 return undefined;73 }74 }75 /**76 * Return snapshot path for file77 */78 public getAllPossiblePathsForFile(filePath: string): string[] {79 return [80 ...this.extensions.map(ext => nodePath.join(nodePath.dirname(filePath), this.dir, nodePath.basename(filePath) + ext)),81 // include js.${ext} too, refs #1182 ...this.extensions.map(ext => nodePath.join(nodePath.dirname(filePath), this.dir, nodePath.basename(filePath, nodePath.extname(filePath)) + ".js" + ext)),83 ];84 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { snapshotPath } = require('differencify');2const { snapshotPath } = require('differencify');3describe('Test', () => {4 it('should create snapshot', async () => {5 const path = await snapshotPath(page, 'test');6 console.log(path);7 });8});9const { snapshot } = require('differencify');10const { snapshot } = require('differencify');11describe('Test', () => {12 it('should create snapshot', async () => {13 await snapshot(page, 'test');14 });15});16const { compare } = require('differencify');17describe('Test', () => {18 it('should create snapshot', async () => {19 const result = await compare(page, 'test');20 expect(result).toBe(true);21 });22});23const { setConfig } = require('differencify');24describe('Test', () => {25 it('should create snapshot', async () => {26 await setConfig({ debug: true });27 await snapshot(page, 'test');28 });29});

Full Screen

Using AI Code Generation

copy

Full Screen

1const { snapshotPath } = require("differencify");2const { expect } = require("chai");3describe("Test", () => {4 it("should take a snapshot", async () => {5 await element.setValue("Hello World");6 const image = await browser.saveElement(element, "search");7 expect(image).to.matchImageSnapshot(snapshotPath("test"));8 });9});10"scripts": {11}12Object {13}14`;15### `differencify.init(options)`

Full Screen

Using AI Code Generation

copy

Full Screen

1const { snapshotPath } = require('differencify')2const path = require('path')3const snapshot = snapshotPath(path.resolve(__dirname, 'snapshots'))4describe('Differencify', () => {5 it('should match the snapshot', async () => {6 const image = await page.screenshot()7 await expect(image).toMatchImageSnapshot(snapshot('example'))8 })9})

Full Screen

Using AI Code Generation

copy

Full Screen

1const differencify = require('differencify');2const { snapshotPath } = differencify;3const path = require('path');4const { Selector } = require('testcafe');5test('Test Google', async t => {6 const searchInput = Selector('input[name=q]');7 const searchButton = Selector('input[name=btnK]');8 .typeText(searchInput, 'testcafe')9 .click(searchButton)10 .wait(5000);11 await t.takeScreenshot(snapshotPath(path.join(__dirname, 'snapshots', 'testcafe.png')));12});13Default: `path.join(__dirname, 'snapshots')`14Default: `path.join(__dirname, 'debug')`15Default: `{}`

Full Screen

Using AI Code Generation

copy

Full Screen

1const { snapshotPath } = require('differencify');2const { expect } = require('chai');3describe('test', () => {4 it('should return a path to the snapshot', () => {5 const snapshot = snapshotPath('test');6 expect(snapshot).to.equal('test/__snapshots__/test.js/test.snap');7 });8});9const { snapshotPath } = require('differencify');10const { expect } = require('chai');11describe('test', () => {12 it('should return a path to the snapshot', () => {13 const snapshot = snapshotPath('test');14 expect(snapshot).to.equal('test/__snapshots__/test.js/test.snap');15 });16});17const { snapshotPath } = require('differencify');18const { expect } = require('chai');19describe('test', () => {20 it('should return a path to the snapshot', () => {21 const snapshot = snapshotPath('test');22 expect(snapshot).to.equal('test/__snapshots__/test.spec.js/test.snap');23 });24});25const { snapshotPath } = require('differencify');26const { expect } = require('chai');27describe('test', () => {28 it('should return a path to the snapshot', () => {29 const snapshot = snapshotPath('test');30 expect(snapshot).to.equal('test/__snapshots__/test.test.js/test.snap');31 });32});33const { snapshotPath } = require('differencify');34const { expect } = require('chai');35describe('test', () => {36 it('should return a path to the snapshot', () => {37 const snapshot = snapshotPath('test');38 expect(snapshot).to.equal('test/__snapshots__/test.e2e.js/test.snap');39 });40});41const { snapshotPath } = require('differencify');42const { expect } = require('chai');43describe('test', () => {44 it('should return a path to

Full Screen

Using AI Code Generation

copy

Full Screen

1const snapshotPath = require('differencify').snapshotPath2const path = require('path')3describe('test', () => {4 it('test', () => {5 browser.url('/')6 const snapshot = snapshotPath(path.join(__dirname, 'test.js'))7 browser.checkElement('body', snapshot)8 })9})

Full Screen

Using AI Code Generation

copy

Full Screen

1const snapshotPath = require('differencify').snapshotPath;2const path = require('path');3const snapshotPath = snapshotPath(path.join(__dirname, 'test.js'));4const snapshotPath = require('differencify').snapshotPath;5const snapshotPath = snapshotPath('test.js');6const snapshotPath = require('differencify').snapshotPath;7const path = require('path');8const snapshotPath = snapshotPath(path.join(__dirname, 'test.js'), 'snapshot');9const snapshotPath = require('differencify').snapshotPath;10const snapshotPath = snapshotPath('test.js', 'snapshot');11const snapshotPath = require('differencify').snapshotPath;12const path = require('path');13const snapshotPath = snapshotPath(path.join(__dirname, 'test.js'), 'snapshot', 'snapshot');14const snapshotPath = require('differencify').snapshotPath;15const snapshotPath = snapshotPath('test.js', 'snapshot', 'snapshot');16const snapshotPath = require('differencify').snapshotPath;17const path = require('path');18const snapshotPath = snapshotPath(path.join(__dirname, 'test.js'), 'snapshot', 'snapshot', 'snapshot');19const snapshotPath = require('differencify').snapshotPath;20const snapshotPath = snapshotPath('test.js', 'snapshot', 'snapshot', 'snapshot');

Full Screen

Using AI Code Generation

copy

Full Screen

1const { snapshotPath } = require("differencify");2const path = require("path");3const fileName = path.basename(__filename);4const snapshotPath = snapshotPath(fileName);5console.log(snapshotPath);6const { snapshotPath } = require("differencify");7const snapshotPath = snapshotPath(__filename);8console.log(snapshotPath);9const { snapshotPath } = require("differencify");10const snapshotPath = snapshotPath();11console.log(snapshotPath);12const { snapshotPath } = require("differencify");13const fileName = path.basename(__filename);14const snapshotPath = snapshotPath(fileName, { customSnapshotsDir: "test/snapshots" });15console.log(snapshotPath);16const { snapshotPath } = require("differencify");17const fileName = path.basename(__filename);18const snapshotPath = snapshotPath(fileName, { customSnapshotsDir: "./test/snapshots" });19console.log(snapshotPath);20const { snapshotPath } = require("differencify");21const fileName = path.basename(__filename);22const snapshotPath = snapshotPath(fileName, { customSnapshotsDir: "test/snapshots" });23console.log(snapshotPath);24const { snapshotPath } = require("differencify");25const fileName = path.basename(__filename);26const snapshotPath = snapshotPath(fileName, { customSnapshotsDir: "./test/snapshots" });27console.log(snapshotPath);

Full Screen

Using AI Code Generation

copy

Full Screen

1const { snapshotPath } = require('differencify');2const path = require('path');3const snapshotPath = snapshotPath(path.join(__dirname, 'my-snapshots'));4### `snapshotPath(snapshotDir, options)`5### `snapshotPath.getSnapshotPath(options)`6MIT © [Pavithra Kodmad](

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run differencify automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful