Best JavaScript code snippet using puppeteer
integration.test.js
Source:integration.test.js
...10 it('simple', async () => {11 await differencify12 .init()13 .newPage()14 .setViewport({ width: 1600, height: 1200 })15 .goto('http://example.com/')16 .waitFor(1000)17 .screenshot()18 .toMatchSnapshot()19 .close()20 .end();21 }, 30000);22 it('simple unchained', async () => {23 const target = differencify.init({ chain: false });24 const page = await target.newPage();25 await page.goto('http://example.com/');26 await page.setViewport({ width: 1600, height: 1200 });27 await page.waitFor(1000);28 const image = await page.screenshot();29 const result = await target.toMatchSnapshot(image);30 await page.close();31 expect(result).toEqual(true);32 }, 30000);33 it('Launch new browser per test', async () => {34 await differencify35 .init()36 .launch({ args: ['--no-sandbox', '--disable-setuid-sandbox'] })37 .newPage()38 .setViewport({ width: 1600, height: 1200 })39 .goto('http://example.com/')40 .waitFor(1000)41 .screenshot()42 .toMatchSnapshot()43 .close()44 .end();45 }, 30000);46 it('Launch new browser per test when unchained', async () => {47 const target = differencify.init({ chain: false });48 await target.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox'] });49 const page = await target.newPage();50 await page.goto('http://example.com/');51 await page.setViewport({ width: 1600, height: 1200 });52 await page.waitFor(1000);53 const image = await page.screenshot();54 const result = await target.toMatchSnapshot(image);55 await page.close();56 await target.close();57 expect(result).toEqual(true);58 }, 30000);59 it('Using result function', async () => {60 await differencify61 .init()62 .newPage()63 .setViewport({ width: 1600, height: 1200 })64 .goto('http://example.com/')65 .waitFor(1000)66 .title()67 .result((title) => {68 expect(title).toEqual('Example Domain');69 })70 .screenshot()71 .toMatchSnapshot()72 .close()73 .end();74 }, 30000);75 it('Using toMatchSnapshot callback for result details', async () => {76 await differencify77 .init()78 .newPage()79 .setViewport({ width: 1600, height: 1200 })80 .goto('http://example.com/')81 .waitFor(1000)82 .title()83 .screenshot()84 .toMatchSnapshot((resultDetail) => {85 expect(resultDetail).toEqual({86 testConfig: {87 chain: true,88 imageType: 'png',89 isJest: true,90 isUpdate: false,91 testId: 6,92 testName: 'Differencify Using toMatchSnapshot callback for result details',93 testNameProvided: false,94 testPath: '/differencify/src/integration.tests/integration.test.js',95 },96 testResult: {97 diffPercent: 0,98 distance: 0,99 matched: true,100 snapshotPath: '/differencify/src/integration.tests/__image_snapshots__/Differencify Using toMatchSnapshot callback for result details.snap.png',101 },102 });103 })104 .close()105 .end();106 }, 30000);107 it('Using toMatchSnapshot callback for result details when unchained', async () => {108 const target = differencify.init({ chain: false });109 await target.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox'] });110 const page = await target.newPage();111 await page.goto('http://example.com/');112 await page.setViewport({ width: 1600, height: 1200 });113 await page.waitFor(1000);114 const image = await page.screenshot();115 await target.toMatchSnapshot(image, (resultDetail) => {116 expect(resultDetail).toEqual({117 testConfig: {118 chain: false,119 imageType: undefined,120 isJest: true,121 isUpdate: false,122 newWindow: true,123 testId: 7,124 testName: 'Differencify Using toMatchSnapshot callback for result details when unchained',125 testNameProvided: false,126 testPath: '/differencify/src/integration.tests/integration.test.js',127 },128 testResult: {129 diffPercent: 0,130 distance: 0,131 matched: true,132 snapshotPath: '/differencify/src/integration.tests/__image_snapshots__/Differencify Using toMatchSnapshot callback for result details when unchained.snap.png',133 },134 });135 });136 await page.close();137 await target.close();138 }, 30000);139 it('Context switching when chained', async () => {140 await differencify141 .init()142 .newPage()143 .tracing144 .start({ path: 'trace.json' })145 .page146 .setViewport({ width: 1600, height: 1200 })147 .goto('http://example.com/')148 .waitFor(1000)149 .keyboard150 .press('Space')151 .tracing152 .stop()153 .page154 .screenshot()155 .toMatchSnapshot()156 .close()157 .end();158 }, 30000);159 it('Calling Puppeteer specific functions when chained: console', async () => {160 await differencify161 .init()162 .newPage()163 .on('console', (msg) => {164 for (let i = 0; i < msg.args.length; i += 1) {165 expect(`${msg.args[i]}`).toEqual('JSHandle:hello');166 }167 })168 .evaluate(() => console.log('hello'))169 .close()170 .end();171 }, 30000);172 it('Calling Puppeteer specific functions when chained: dialog', async () => {173 await differencify174 .init()175 .newPage()176 .on('dialog', async (dialog) => {177 expect(dialog.message()).toEqual('1');178 await dialog.dismiss();179 })180 .evaluate(() => alert('1'))181 .close()182 .end();183 }, 30000);184 it('Continue on chained object', async () => {185 await differencify186 .init()187 .newPage()188 .goto('http://example.com/')189 .mainFrame()190 .then191 .url()192 .result((url) => {193 expect(url).toEqual('http://example.com/');194 })195 .close()196 .end();197 }, 30000);198 it('Multiple toMatchSnapshot on chained object', async () => {199 await differencify200 .init()201 .newPage()202 .goto('http://example.com/')203 .waitFor(1000)204 .screenshot()205 .toMatchSnapshot()206 .result((result) => {207 expect(result).toEqual(true);208 })209 .goto('http://example.com/')210 .waitFor(1000)211 .screenshot()212 .toMatchSnapshot()213 .result((result) => {214 expect(result).toEqual(true);215 })216 .close()217 .end();218 }, 30000);219 it('Multiple toMatchSnapshot when unchained', async () => {220 const target = differencify.init({ chain: false });221 const page = await target.newPage();222 await page.goto('http://example.com/');223 await page.setViewport({ width: 1600, height: 1200 });224 await page.waitFor(1000);225 const image = await page.screenshot();226 const result = await target.toMatchSnapshot(image);227 await page.goto('http://example.net/');228 await page.setViewport({ width: 1600, height: 1200 });229 await page.waitFor(1000);230 const image2 = await page.screenshot();231 const result2 = await target.toMatchSnapshot(image2);232 await page.close();233 expect(result).toEqual(true);234 expect(result2).toEqual(true);235 }, 30000);236 it('Custom test name', async () => {237 const target = differencify.init({238 testName: 'test1',239 chain: false,240 });241 const page = await target.newPage();242 await page.goto('http://example.com/');243 await page.setViewport({ width: 1600, height: 1200 });244 await page.waitFor(1000);245 const image = await page.screenshot();246 const result = await target.toMatchSnapshot(image);247 await page.close();248 expect(result).toEqual(true);249 }, 30000);250 it('Custom test path', async () => {251 const customDifferencify = new Differencify({252 imageSnapshotPath: './src/integration.tests/__image_snapshots__/custom_test_path',253 debug: true,254 });255 await customDifferencify.launchBrowser({ args: ['--no-sandbox', '--disable-setuid-sandbox'] });256 const target = customDifferencify.init({257 chain: false,258 });259 const page = await target.newPage();260 await page.setViewport({ width: 1600, height: 1200 });261 await page.goto('http://example.com/');262 await page.waitFor(1000);263 const image = await page.screenshot();264 const result = await target.toMatchSnapshot(image);265 await page.close();266 await customDifferencify.cleanup();267 expect(result).toEqual(true);268 }, 30000);269 it('Freeze image in page', async () => {270 await differencify271 .init()272 .newPage()273 .setViewport({ width: 1600, height: 1200 })274 .goto('https://i.giphy.com/media/xTiTnoUnHxVaaVNWhO/giphy.webp')275 .waitFor('body > img')276 .freezeImage('body > img')277 .screenshot()278 .toMatchSnapshot()279 .close()280 .end();281 }, 30000);282 it('simple with mock requests', async () => {283 await differencify284 .init()285 .newPage()286 .mockRequests()287 .setViewport({ width: 1600, height: 1200 })288 .goto('http://example.com/')289 .waitFor(1000)290 .screenshot()291 .toMatchSnapshot()292 .close()293 .end();294 }, 30000);295 it('simple unchained with mock requests', async () => {296 const target = differencify.init({ chain: false });297 const page = await target.newPage();298 await target.mockRequests();299 await page.goto('http://example.com/');300 await page.setViewport({ width: 1600, height: 1200 });301 await page.waitFor(1000);302 const image = await page.screenshot();303 const result = await target.toMatchSnapshot(image);304 await page.close();305 expect(result).toEqual(true);306 }, 30000);307 it('simple with mock requests', async () => {308 process.env.CI = 'true'; // This will simulate CI/CD environment309 await differencify310 .init()311 .newPage()312 .mockRequests()313 .setViewport({ width: 1600, height: 1200 })314 .goto('http://example.com/')315 .waitFor(1000)316 .screenshot()317 .toMatchSnapshot()318 .close()319 .end();320 }, 30000);321 it('simple unchained with mock requests', async () => {322 process.env.CI = 'true'; // This will simulate CI/CD environment323 const target = differencify.init({ chain: false });324 const page = await target.newPage();325 await target.mockRequests();326 await page.goto('http://example.com/');327 await page.setViewport({ width: 1600, height: 1200 });328 await page.waitFor(1000);329 const image = await page.screenshot();330 const result = await target.toMatchSnapshot(image);331 await page.close();332 expect(result).toEqual(true);333 }, 30000);334 it('mock requests and replace image', async () => {335 await differencify336 .init()337 .newPage()338 .mockRequests({ replaceImage: true })339 .setViewport({ width: 1600, height: 1200 })340 .goto('https://nimasoroush.github.io/differencify/')341 .waitFor(1000)342 .screenshot()343 .toMatchSnapshot()344 .close()345 .end();346 }, 30000);347 it('mock requests and replace image', async () => {348 process.env.CI = 'true'; // This will simulate CI/CD environment349 await differencify350 .init()351 .newPage()352 .mockRequests({ replaceImage: true })353 .setViewport({ width: 1600, height: 1200 })354 .goto('https://nimasoroush.github.io/differencify/')355 .waitFor(1000)356 .screenshot()357 .toMatchSnapshot()358 .close()359 .end();360 }, 30000);...
setViewport_test.js
Source:setViewport_test.js
...67 hflip: false,68 vflip: false69 };70 // Act71 setViewport(element, newViewport);72 // Assert73 const viewport = getViewport(element);74 Object.keys(newViewport).forEach((key) => {75 assert.deepEqual(newViewport[key], viewport[key]);76 });77 });78 it('should prevent windowWidth from getting too small', function () {79 const element = this.element;80 // Arrange81 this.viewport.voi.windowWidth = 0.0000000000001;82 // Act83 setViewport(element, this.viewport);84 // Assert85 const viewport = getViewport(element);86 assert.equal(viewport.voi.windowWidth, MIN_WINDOW_WIDTH);87 });88 it('should prevent scale from getting too small', function () {89 const element = this.element;90 // Arrange91 this.viewport.scale = 0.0000000000001;92 // Act93 setViewport(element, this.viewport);94 // Assert95 const viewport = getViewport(element);96 assert.equal(viewport.scale, MIN_VIEWPORT_SCALE);97 });98 it('should normalize rotation values above 359 degrees', function () {99 const element = this.element;100 // Arrange101 this.viewport.rotation = 365;102 // Act103 setViewport(element, this.viewport);104 // Assert105 const viewport = getViewport(element);106 assert.equal(viewport.rotation, 5);107 });108 it('should normalize rotation values below 0 degrees', function () {109 const element = this.element;110 // Arrange111 this.viewport.rotation = -5;112 // Act113 setViewport(element, this.viewport);114 // Assert115 const viewport = getViewport(element);116 assert.equal(viewport.rotation, 355);117 });118 afterEach(function () {119 disable(this.element);120 });...
Map.js
Source:Map.js
...12 longitude: -71.43,13 zoom: 714 });15 const goToChicago = () => {16 setViewport({17 ...viewport,18 longitude: -87.6298,19 latitude: 41.8781,20 zoom: 14,21 transitionDuration: 4000,22 transitionInterpolator: new FlyToInterpolator(),23 transitionEasing: easeCubic24 });25 };26 const goToBoston = () => {27 setViewport({28 ...viewport,29 longitude: -71.0589,30 latitude: 42.3601,31 zoom: 14,32 transitionDuration: 4000,33 transitionInterpolator: new FlyToInterpolator(),34 transitionEasing: easeCubic35 });36 };37 const goToNYC = () => {38 setViewport({39 ...viewport,40 longitude: -74.1,41 latitude: 40.7,42 zoom: 14,43 transitionDuration: 4000,44 transitionInterpolator: new FlyToInterpolator(),45 transitionEasing: easeCubic46 });47 };48 const goToSF = () => {49 const { longitude, latitude, zoom } = new WebMercatorViewport(viewport)50 .fitBounds([[-122.4, 37.7], [-122.5, 37.8]], {51 padding: 20,52 offset: [0, -100]53 });54 setViewport({55 ...viewport,56 longitude,57 latitude,58 zoom,59 transitionDuration: 4000,60 // transitionInterpolator: new FlyToInterpolator(),61 transitionInterpolator: new LinearInterpolator(),62 transitionEasing: easeCubic63 });64 };65 const goToAtlanta = () => {66 return (<FlyTo67 setViewport={68 setViewport({69 viewport: viewport,70 longitude: -84.3880,71 latitude: 33.7490,72 zoom: 14,73 transitionDuration: 4000,74 transitionInterpolator: new FlyToInterpolator(),75 transitionEasing: easeCubic76 })}77 />)78 }79 return (80 <div>81 <button className={styles.FlyButton} onClick={goToChicago}>Chicago</button>82 <button className={styles.FlyButton} onClick={goToBoston}>Boston</button>...
viewport.js
Source:viewport.js
...23 global.callNative = originalCallNative24 console.warn.reset()25 })26 it('invalid setViewport', () => {27 setViewport()28 expect(global.callNative.callCount).to.be.equal(0)29 setViewport({})30 expect(global.callNative.callCount).to.be.equal(0)31 })32 it('setViewport', () => {33 setViewport(mockApp, {})34 expect(global.callNative.callCount).to.be.equal(1)35 setViewport(mockApp, { width: 640 })36 expect(global.callNative.callCount).to.be.equal(2)37 setViewport(mockApp, { width: 'device-width' })38 expect(global.callNative.callCount).to.be.equal(3)39 })40 it('validateViewport', () => {41 expect(validateViewport()).to.be.false42 expect(console.warn.callCount).to.be.equal(1)43 expect(validateViewport({})).to.be.false44 expect(console.warn.callCount).to.be.equal(2)45 expect(validateViewport({ width: 200 })).to.be.true46 expect(console.warn.callCount).to.be.equal(2)47 expect(validateViewport({ width: 'device-width' })).to.be.true48 expect(console.warn.callCount).to.be.equal(2)49 expect(validateViewport({ width: 'initial-width' })).to.be.false50 expect(console.warn.callCount).to.be.equal(3)51 })...
e2e.spec.js
Source:e2e.spec.js
2 it('loading the home page', () => {3 cy.visit('http://zero.webappsecurity.com/index.html')4 })5 it('full HD Layout for Home Page', () => {6 cy.setViewport([1920, 1080])7 cy.matchImageSnapshot()8 })9 it('iphone Layout for Home Page', () => {10 cy.setViewport('iphone-x')11 cy.matchImageSnapshot()12 })13})14describe('E2E Visual Regression Login Page', () => {15 it('clicking on signin button', () => {16 cy.get('#signin_button').click()17 })18 it('full HD Layout for Login Page', () => {19 cy.setViewport([1920, 1080])20 cy.matchImageSnapshot({21 failureThreshold: 1.0,22 })23 })24 it('iphone Layout for Login Page', () => {25 cy.setViewport('iphone-x')26 cy.matchImageSnapshot({27 failureThreshold: 1.0,28 })29 })30})31describe('E2E Visual Regression Login Page Details', () => {32 it('should fill in login details', () => {33 cy.get('#user_login').type('username')34 cy.get('#user_password').type('password')35 cy.get('#user_remember_me').click()36 })37 it('full HD Layout for Login Page Details', () => {38 cy.setViewport([1920, 1080])39 cy.matchImageSnapshot()40 })41 it('iphone Layout for Login Page Details', () => {42 cy.setViewport('iphone-x')43 cy.matchImageSnapshot()44 })45})46describe('E2E Visual Regression User Login', () => {47 it('should fill in login details', () => {48 cy.get('.btn.btn-primary').click()49 })50 it('full HD Layout for User Login', () => {51 cy.setViewport([1920, 1080])52 cy.matchImageSnapshot()53 })54 it('iphone Layout for User Login', () => {55 cy.setViewport('iphone-x')56 cy.matchImageSnapshot()57 })...
LocationsPage.jsx
Source:LocationsPage.jsx
1import React from 'react';2import {Container, Row, Col} from 'reactstrap';3import LocationsBar from '../components/LocationsBar';4import LocationsMap from '../components/LocationsMap';5import LocationsList from '../components/LocationsList';6 7const LocationsPage = ( {TOKEN, viewport, setViewport, shops,8 selectedShop, setSelectedShop, highlightedShop, handleHighlightShop} ) => (9 <Container className="locations">10 <Row className="justify-content-center">11 <h2>BikeGalaxy Locations:</h2>12 </Row>13 <Row>14 <Col md="12" lg="8">15 <LocationsBar16 viewport={viewport}17 setViewport={setViewport}18 />19 <LocationsMap20 TOKEN={TOKEN}21 viewport={viewport}22 setViewport={setViewport}23 shops={shops}24 selectedShop={selectedShop}25 setSelectedShop={setSelectedShop}26 />27 </Col>28 <Col md="12" lg="4">29 <LocationsList30 viewport={viewport}31 setViewport={setViewport}32 shops={shops} 33 highlightedShop={highlightedShop}34 handleHighlightShop={handleHighlightShop}35 />36 </Col>37 </Row> 38 </Container>39) ...
ViewportListener.js
Source:ViewportListener.js
...19 return 'desktop';20 }21 }, [breakpoints.mobile, breakpoints.tablet]);22 const handleResize = useCallback(() => {23 setViewport(checkViewport());24 }, [checkViewport, setViewport]);25 useEffect(() => {26 setViewport(checkViewport());27 window && window.addEventListener('resize', handleResize);28 return () => window.removeEventListener('resize', handleResize);29 }, [checkViewport, handleResize, setViewport]);30 return null;31};32const mapDispatchToProps = dispatch => ({33 setViewport: value => dispatch(setViewport(value)),34});35ViewportListener.propTypes = {36 setViewport: PropTypes.func.isRequired,37};...
setViewport.js
Source:setViewport.js
1'use strict'2module.exports = {3 detect: function (command) {4 return !!command.setViewport5 },6 perform: function (grunt, target, client, command, options) {7 const lastViewport = options.lastViewport8 let setViewport = command.setViewport9 let prefix10 if (!(setViewport.width && setViewport.height)) {11 prefix = 'original '12 setViewport = options.viewport13 } else {14 prefix = ''15 }16 if (setViewport.width === lastViewport.width &&17 setViewport.height === lastViewport.height) {18 grunt.output.writeln('Retaining ' + prefix + 'viewport size ' +19 setViewport.width + 'x' + setViewport.height + '.')20 return Promise.resolve()21 }22 grunt.output.writeln('Resize viewport to ' + prefix +23 setViewport.width + 'x' + setViewport.height + '.')24 lastViewport.width = setViewport.width25 lastViewport.height = setViewport.height26 lastViewport.explicit = true27 return client.setWindowRect(28 null, null, setViewport.width, setViewport.height)29 }...
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!!