Best JavaScript code snippet using differencify
target.test.js
Source:target.test.js
1import puppeteer from 'puppeteer';2import recorder from 'mockeer';3import Target from './target';4import { globalConfig, testConfig } from '../config/defaultConfigs';5import functionToString from '../helpers/functionToString';6import freezeImage from './freezeImage';7import { sanitiseGlobalConfiguration } from './sanitiser';8import jestMatchers from '../utils/jestMatchers';9import compareImage from './compareImage';10import logger from '../utils/logger';11const mockMatcher = jest.fn(() => ({12 message: 'message',13 pass: true,14}));15jestMatchers.toNotError = mockMatcher;16jestMatchers.toMatchImageSnapshot = mockMatcher;17jest.mock('./compareImage');18const mockKeyboard = {19 press: jest.fn(),20};21const pageMocks = {22 goto: jest.fn(),23 click: jest.fn(),24 screenshot: jest.fn(),25 waitFor: jest.fn(),26 evaluate: jest.fn(),27 setViewport: jest.fn(),28 keyboard: mockKeyboard,29};30const mockNewPage = jest.fn(() => (pageMocks));31jest.mock('puppeteer', () => ({32 launch: jest.fn(() => ({33 newPage: mockNewPage,34 })),35 connect: jest.fn(() => ({36 newPage: mockNewPage,37 })),38}));39jest.mock('path', () => ({40 join: jest.fn(() => '/'),41 resolve: jest.fn((a, b, c, d) => `root${b}${d}`),42}));43jest.mock('mockeer');44jest.mock('./compareImage', () => jest.fn(arg => new Promise((resolve, reject) => {45 if (arg.screenshots === './screenshots') {46 return resolve('Saving the diff image to disk');47 }48 return reject(new Error('error'));49})));50jest.mock('./helpers/functionToString');51const mockLog = jest.fn();52const mockTrace = jest.fn();53const mockErr = jest.fn();54jest.mock('./utils/logger', () => ({55 prefix: jest.fn(() => ({56 log: mockLog,57 error: mockErr,58 trace: mockTrace,59 })),60 warn: jest.fn(),61}));62const browser = puppeteer.launch();63const target = new Target(browser, testConfig, sanitiseGlobalConfiguration(globalConfig));64describe('Target', () => {65 afterEach(() => {66 puppeteer.launch.mockClear();67 mockLog.mockClear();68 mockTrace.mockClear();69 mockErr.mockClear();70 functionToString.mockClear();71 mockMatcher.mockClear();72 compareImage.mockClear();73 target.error = false;74 mockNewPage.mockClear();75 logger.warn.mockClear();76 });77 beforeEach(() => {78 target.tab = target.browser.newPage();79 });80 it('launch fn', async () => {81 target.browser = null;82 await target.launch({83 args: [],84 dumpio: false,85 executablePath: undefined,86 headless: true,87 ignoreHTTPSErrors: false,88 slowMo: 0,89 timeout: 30000,90 });91 expect(mockLog).toHaveBeenCalledWith('Launching browser...');92 expect(puppeteer.launch).toHaveBeenCalledWith({93 args: [],94 dumpio: false,95 executablePath: undefined,96 headless: true,97 ignoreHTTPSErrors: false,98 slowMo: 0,99 timeout: 30000,100 });101 expect(mockNewPage).toHaveBeenCalledTimes(1);102 expect(target.testConfig.newWindow).toEqual(true);103 });104 it('connect fn', async () => {105 target.browser = null;106 await target.connect({107 browserWSEndpoint: 'endpoint',108 ignoreHTTPSErrors: false,109 });110 expect(mockLog).toHaveBeenCalledWith('Launching browser...');111 expect(puppeteer.connect).toHaveBeenCalledWith({112 browserWSEndpoint: 'endpoint',113 ignoreHTTPSErrors: false,114 });115 expect(mockNewPage).toHaveBeenCalledTimes(1);116 expect(target.testConfig.newWindow).toEqual(true);117 });118 describe('_handleFunc', () => {119 beforeEach(() => {120 pageMocks.goto.mockClear();121 });122 it('Wont run if error happened', async () => {123 target.error = true;124 await target._handleFunc('url');125 expect(mockLog).toHaveBeenCalledTimes(0);126 });127 it('will return correct property', async () => {128 target.error = false;129 const result = await target._handleFunc('page', 'testConfig');130 expect(result).toEqual({131 debug: false,132 chain: undefined,133 imageSnapshotPath: 'differencify_reports',134 imageSnapshotPathProvided: true,135 saveDifferencifiedImage: true,136 saveCurrentImage: true,137 mismatchThreshold: 0.001,138 newWindow: true,139 });140 expect(mockLog).toHaveBeenCalledWith('Executing page.testConfig step');141 });142 it('will run goto on page', async () => {143 target.error = false;144 await target.newPage();145 const result = await target._handleFunc('page', 'goto', ['http://example.com', {}]);146 expect(pageMocks.goto).toHaveBeenCalledWith('http://example.com', {});147 expect(result).toEqual();148 expect(mockLog).toHaveBeenCalledWith('Executing page.goto step');149 });150 it('will run press on keyboard', async () => {151 target.error = false;152 await target.newPage();153 const result = await target._handleFunc('keyboard', 'press', arguments); // eslint-disable-line no-undef154 expect(mockKeyboard.press).toHaveBeenCalledWith(...arguments); // eslint-disable-line no-undef155 expect(result).toEqual();156 expect(mockLog).toHaveBeenCalledWith('Executing keyboard.press step');157 });158 });159 describe('capture/screenshot', () => {160 beforeEach(() => {161 pageMocks.screenshot.mockClear();162 });163 it('Wont run if error happened', async () => {164 target.error = true;165 await target.capture();166 await target.screenshot();167 expect(mockLog).toHaveBeenCalledTimes(0);168 });169 it('Will run capture correctly', async () => {170 await target.newPage();171 await target.capture({});172 expect(pageMocks.screenshot).toHaveBeenCalledWith({});173 expect(logger.warn).toHaveBeenCalledWith(`capture() will be deprecated, use screenshot() instead.174 Please read the API docs at https://github.com/NimaSoroush/differencify`);175 });176 it('Will run screenshot correctly', async () => {177 await target.newPage();178 await target.screenshot({});179 expect(pageMocks.screenshot).toHaveBeenCalledWith({});180 });181 });182 describe('mockRequests', () => {183 it('calls Mockeer correctly', async () => {184 await target.mockRequests();185 expect(recorder).toHaveBeenCalledTimes(1);186 });187 it('calls Mockeer correctly with options', async () => {188 await target.mockRequests({189 replaceImage: true,190 allowImageRecourses: false,191 });192 expect(recorder).toHaveBeenCalledWith(expect.any(Object), {193 page: expect.any(Object),194 replaceImage: true,195 allowImageRecourses: false,196 });197 });198 });199 describe('wait', () => {200 beforeEach(() => {201 pageMocks.waitFor.mockClear();202 });203 it('Wont run if error happened', async () => {204 target.error = true;205 await target.newPage();206 await target.wait();207 expect(pageMocks.waitFor).not.toHaveBeenCalled();208 });209 it('Will run wait correctly', async () => {210 await target.newPage();211 await target.wait(10);212 expect(pageMocks.waitFor).toHaveBeenCalledWith(10);213 expect(logger.warn).toHaveBeenCalledWith(`wait() will be deprecated, use waitFor() instead.214 Please read the API docs at https://github.com/NimaSoroush/differencify`);215 });216 });217 describe('execute', () => {218 beforeEach(() => {219 pageMocks.evaluate.mockClear();220 });221 it('Wont run if error happened', async () => {222 target.error = true;223 await target.execute();224 expect(pageMocks.evaluate).not.toHaveBeenCalled();225 });226 it('Will run correctly', async () => {227 await target.newPage();228 await target.execute('exp');229 expect(pageMocks.evaluate).toHaveBeenCalledWith('exp');230 expect(logger.warn).toHaveBeenCalledWith(`execute() will be deprecated, use evaluate() instead.231 Please read the API docs at https://github.com/NimaSoroush/differencify`);232 });233 });234 describe('resize', () => {235 beforeEach(() => {236 pageMocks.setViewport.mockClear();237 });238 it('Wont run if error happened', async () => {239 target.error = true;240 await target.resize();241 expect(pageMocks.setViewport).not.toHaveBeenCalled();242 });243 it('Will run correctly', async () => {244 await target.resize('exp');245 expect(pageMocks.setViewport).toHaveBeenCalledWith('exp');246 expect(logger.warn).toHaveBeenCalledWith(`resize() will be deprecated, use setViewport() instead.247 Please read the API docs at https://github.com/NimaSoroush/differencify`);248 });249 });250 describe('toMatchSnapshot', () => {251 it('will set test to jest mode', async () => {252 target.isJest();253 target.toMatchSnapshot();254 expect(target.testStats).not.toBeNull();255 expect(target.testConfig.testName).toEqual('Target toMatchSnapshot will set test to jest mode');256 expect(target.testId).toEqual(1);257 expect(mockTrace).toHaveBeenCalledTimes(0);258 });259 it('will test name with numbers if several times called', async () => {260 target.testId = 0;261 target.isJest();262 target.toMatchSnapshot();263 target.toMatchSnapshot();264 expect(target.testConfig.isJest).toEqual(true);265 expect(target.testStats).not.toBeNull();266 expect(target.testConfig.testName)267 .toEqual('Target toMatchSnapshot will test name with numbers if several times called 1');268 expect(target.testId).toEqual(2);269 expect(mockErr).toHaveBeenCalledTimes(0);270 });271 it('Will respect to testName if it is provided', async () => {272 target.testId = 0;273 target.testConfig.testName = 'test';274 target.testConfig.testNameProvided = true;275 target.isJest();276 target.toMatchSnapshot();277 expect(target.testConfig.isJest).toEqual(true);278 expect(target.testStats).not.toBeNull();279 expect(target.testConfig.testName)280 .toEqual('test');281 expect(target.testId).toEqual(1);282 expect(mockErr).toHaveBeenCalledTimes(0);283 });284 it('Will respect to testName if it is provided', async () => {285 target.testId = 0;286 target.testConfig.testName = 'test';287 target.testConfig.testNameProvided = true;288 target.isJest();289 target.toMatchSnapshot();290 target.toMatchSnapshot();291 expect(target.testConfig.isJest).toEqual(true);292 expect(target.testStats).not.toBeNull();293 expect(target.testConfig.testName)294 .toEqual('test 1');295 expect(target.testId).toEqual(2);296 expect(mockErr).toHaveBeenCalledTimes(0);297 });298 });299 describe('isJest', () => {300 it('will set test to jest mode', async () => {301 target.isJest();302 expect(target.testConfig.isJest).toEqual(true);303 expect(target.testStats).not.toBeNull();304 });305 });306 describe('_evaluateResult', () => {307 it('it calls toNotError if error happens in any steps when in jest mode', async () => {308 target.error = new Error('Error happened');309 const result = await target._evaluateResult();310 expect(jestMatchers.toNotError).toHaveBeenCalled();311 expect(result).toEqual(false);312 });313 it('it wont calls toMatchImageSnapshot when in jest mode and compareImage throws', async () => {314 const result = await target._evaluateResult();315 expect(compareImage).toHaveBeenCalled();316 expect(jestMatchers.toMatchImageSnapshot).not.toHaveBeenCalled();317 expect(result).toEqual(false);318 });319 it('it calls toMatchImageSnapshot when in jest mode', async () => {320 compareImage.mockReturnValueOnce({ matched: true });321 const result = await target._evaluateResult();322 expect(compareImage).toHaveBeenCalled();323 expect(jestMatchers.toMatchImageSnapshot).toHaveBeenCalled();324 expect(result).toEqual(true);325 });326 });327 describe('FreezeImage', () => {328 beforeEach(() => {329 pageMocks.evaluate.mockClear();330 });331 it('Wont run if error happened', async () => {332 target.error = true;333 await target.freezeImage();334 expect(mockLog).toHaveBeenCalledTimes(0);335 });336 it('Existing selector', async () => {337 pageMocks.evaluate.mockReturnValueOnce(true);338 functionToString.mockReturnValueOnce('return string function');339 await target.freezeImage('selector');340 expect(mockLog).toHaveBeenCalledWith('Freezing image selector in browser');341 expect(mockErr).toHaveBeenCalledTimes(0);342 expect(pageMocks.evaluate).toHaveBeenCalledWith('return string function');343 expect(functionToString).toHaveBeenCalledWith(freezeImage, 'selector');344 });345 it('FreezeImage: non-existing selector', async () => {346 pageMocks.evaluate.mockReturnValueOnce(false);347 functionToString.mockReturnValueOnce('return string function');348 await target.freezeImage('selector');349 expect(mockLog).toHaveBeenCalledWith('Freezing image selector in browser');350 expect(mockTrace).toHaveBeenCalledWith('Unable to freeze image with selector selector');351 expect(pageMocks.evaluate).toHaveBeenCalledWith('return string function');352 expect(functionToString).toHaveBeenCalledWith(freezeImage, 'selector');353 });354 });...
Using AI Code Generation
1const differencify = require("differencify");2const differencifyConfig = require("./differencify.config.js");3differencify.init(differencifyConfig);4const differencify = require("differencify");5const differencifyConfig = require("./differencify.config.js");6differencify.init(differencifyConfig);7const differencify = require("differencify");8const differencifyConfig = require("./differencify.config.js");9differencify.init(differencifyConfig);10const differencify = require("differencify");11const differencifyConfig = require("./differencify.config.js");12differencify.init(differencifyConfig);13const differencify = require("differencify");14const differencifyConfig = require("./differencify.config.js");15differencify.init(differencifyConfig);16const differencify = require("differencify");17const differencifyConfig = require("./differencify.config.js");18differencify.init(differencifyConfig);19const differencify = require("differencify");20const differencifyConfig = require("./differencify.config.js");21differencify.init(differencifyConfig);22const differencify = require("differencify");23const differencifyConfig = require("./differencify.config.js");24differencify.init(differencifyConfig);25const differencify = require("differencify");26const differencifyConfig = require("./differencify.config.js");27differencify.init(differencifyConfig);28const differencify = require("differencify");29const differencifyConfig = require("./differencify.config.js");30differencify.init(differencifyConfig);
Using AI Code Generation
1const differencify = require("differencify");2const differencifyConfig = require("./differencify.config.js");3const differencifyInstance = differencify.init(differencifyConfig);4test("test", async () => {5 const page = await differencifyInstance.mockNewPage();6 await page.waitForSelector("input[name=q]");7 await page.type("input[name=q]", "Hello World");8 await page.click("input[type=submit]");9 await page.waitForSelector("div#search");10 await page.screenshot({ path: "test.png" });11});
Using AI Code Generation
1const { mockNewPage } = require('differencify');2const puppeteer = require('puppeteer');3const originalNewPage = puppeteer.launch().then(browser => browser.newPage);4puppeteer.launch = () => Promise.resolve({5 newPage: mockNewPage(originalNewPage)6});7const differencify = require('differencify');8differencify.init({});9const { expect } = require('chai');10const { getDriver } = require('differencify');11describe('test', () => {12 it('should work', async () => {13 const driver = await getDriver();14 const image = await driver.takeScreenshot();15 expect(image).to.matchImage('google');16 });17});18describe('test', () => {19 it('should work', async () => {20 const driver = await getDriver();21 const image = await driver.takeScreenshot();22 expect(image).to.matchImage('google');23 });24});25describe('test', () => {26 it('should work', async () => {27 const driver = await getDriver();28 const image = await driver.takeScreenshot();29 expect(image).to.matchImage('google');30 });31});32describe('test', () => {33 it('should work', async () => {34 const driver = await getDriver();35 const image = await driver.takeScreenshot();36 expect(image).to.matchImage('google');37 });38});39describe('test', () => {40 it('should work', async () => {41 const driver = await getDriver();42 const image = await driver.takeScreenshot();43 expect(image).to.matchImage('google');44 });45});46describe('test', () => {47 it('should work', async () => {48 const driver = await getDriver();49 const image = await driver.takeScreenshot();
Using AI Code Generation
1const { mockNewPage } = require('differencify');2const { mockNewPage } = require('differencify');3describe('My Test', () => {4 let page;5 let browser;6 beforeAll(async () => {7 browser = await puppeteer.launch();8 page = await browser.newPage();9 await mockNewPage(page);10 });11 afterAll(async () => {12 await browser.close();13 });14 test('My Test', async () => {15 await page.screenshot({ path: 'google.png' });16 await page.differencify.toMatchSnapshot('google');17 });18});19module.exports = {20 transform: {21 },22};
Using AI Code Generation
1const differencify = require('differencify');2const differencifyConfig = {3 diffOptions: {4 },5};6const differencifyInstance = differencify.init(differencifyConfig);7const { mockNewPage } = differencifyInstance;8const { browser, page } = await mockNewPage();9await page.screenshot({path: 'google.png'});10await browser.close();11const differencify = require('differencify');12const differencifyConfig = {13 diffOptions: {14 },15};16const differencifyInstance = differencify.init(differencifyConfig);17const { expect } = differencifyInstance;18describe('Google', () => {19 it('should look the same', async () => {20 await expect(page).toMatchScreenshot();21 });22});23const differencify = require('differencify');24const differencifyConfig = {25 diffOptions: {26 },27};28const differencifyInstance = differencify.init(differencifyConfig);29const { expect } = differencifyInstance;30describe('Google', () => {31 it('should look the same', async () => {32 await expect(page).toMatchScreenshot();33 });34});35const differencify = require('differencify');36const differencifyConfig = {37 diffOptions: {38 },39};
Using AI Code Generation
1const differencify = require('differencify')2const differencifyConfig = {3}4const differencifyInstance = differencify.init(differencifyConfig)5const differencifyInstance = require('./test')6const { expect } = require('chai')7describe('test', () => {8 it('should test', async () => {9 const page = await differencifyInstance.mockNewPage()10 })11})12differencify.init(options)13const differencify = require('differencify')14const differencifyInstance = differencify.init({15})16differencifyInstance.mockNewPage()17differencifyInstance.mockNewPage(options)18const differencify = require('differencify')19const differencifyInstance = differencify.init({20})21const page = differencifyInstance.mockNewPage({22})23differencifyInstance.mockNewPage(options).screenshot(options)24differencifyInstance.mockNewPage(options).screenshot(options).toMatchImageSnapshot(options)25differencifyInstance.mockNewPage(options).screenshot(options).toMatchImageSnapshot(options).toMatchImageSnapshot(options)26differencifyInstance.mockNewPage(options).screenshot(options).toMatchImageSnapshot(options).toMatchImageSnapshot(options).toMatchImageSnapshot(options)27differencifyInstance.mockNewPage(options).screenshot(options).toMatchImageSnapshot(options).toMatchImageSnapshot(options).toMatchImageSnapshot(options).toMatchImageSnapshot(options)28differencifyInstance.mockNewPage(options).screenshot(options).toMatchImageSnapshot(options).toMatchImageSnapshot(options).toMatchImageSnapshot(options).toMatchImageSnapshot(options).toMatchImage
Using AI Code Generation
1const differencify = require('differencify');2const { mockNewPage } = differencify;3const page = await mockNewPage({4 viewport: { width: 1000, height: 800 },5});6await page.screenshot({path: 'screenshot.png'});7await page.close();8### `mockNewPage(options)`9### `mockNewPage(options).screenshot(options)`10- `clip` (`object`): An object which specifies clipping of the resulting image. Should have the following fields:11 - `x` (`number`): x-coordinate of top-left corner of clip area
Using AI Code Generation
1const { mockNewPage } = require('differencify');2describe('My test', () => {3 it('should work', async () => {4 const page = await browser.newPage();5 mockNewPage(page);6 await page.screenshot({ path: 'example.png' });7 });8});9- `updateSnapshot` (default `false`): if `true`, the snapshot will be updated10- `threshold` (default `0.05`): the threshold to use for the image comparison11- `cleanup` (default `true`): if `true`, the snapshot will be deleted after the test is done12- `updatePassedSnapshot` (default `false`): if `true`, the snapshot will be updated if the test passed13const { mockNewPage } = require('differencify');14describe('My test', () => {15 it('should work', async () => {16 const page = await browser.newPage();17 mockNewPage(page);18 await page.screenshot({ path: 'example.png' });19 }, {20 });21});22const { mockNewPage } = require('differencify');23describe('My test', () => {24 it('should work', async () => {25 const page = await browser.newPage();26 mockNewPage(page);27 await page.screenshot({ path: 'example.png' });28 }, {29 });30});
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!