How to achieve Device emulation with the puppeteer. How to run a puppeteer script on different sizes of the screen like Mobile, Tablet, or desktop Etc.
Device emulation in puppeteer
We can perform device emulation in puppeteer by changing some lines of code. Puppeteer has a rich library that contains an array of devices to perform automation on the different sizes of like mobile and tablet. Also, we can change the viewport to verify a dynamic view.
Let’s see all the device emulation example in puppeteer
Change viewport in puppeteer
Puppeteer has setViewport({width:, height:}). This function takes an array of view size and returns the dynamic viewport of that size. let’s see an example.
Viewport example in puppeteer
it("Desktop View",async()=>{ await page.setViewport({width:1650, height:1050}) await page.waitFor(5000); })
Mobile device emulation in puppeteer
puppeteer.devices[‘iPhone X’] function is used to change viewport according to the mobile device. Let’s see an example of a mobile device emulation in puppeteer.
Mobile device emulation example in puppeteer
//Open Mobile view it("Mobile View", async()=>{ const mobile = puppeteer.devices['iPhone X'] page.emulate(mobile) await page.waitFor(5000); })
Table emulation in puppeteer
//Open tablet view it("Tablet View", async()=>{ const tablet = puppeteer.devices['iPad landscape'] await page.emulate(tablet) await page.waitFor(5000); })
Device Emulation example in puppeteer
In this device emulation example, we are using all the three above examples in a puppeteer script.
TestCase:
- Launch browser.
- Load URL.
- Change the viewport as desktop View.
- Change the device view as mobile.
- Change the device view as a tablet.
const puppeteer = require('puppeteer') describe("Device emulation in puppeteer",()=>{ let browser let page before(async function(){ browser = await puppeteer.launch({ headless:false, slowMo:100 }) page = await browser.newPage() await page.goto("https://devexpress.github.io/testcafe/example/") }) //Open the desktop view it("Desktop View",async()=>{ await page.setViewport({width:1650, height:1050}) await page.waitFor(5000); }) //Open tablet view it("Tablet View", async()=>{ const tablet = puppeteer.devices['iPad landscape'] await page.emulate(tablet) await page.waitFor(5000); }) //Open Mobile view it("Mobile View", async()=>{ const mobile = puppeteer.devices['iPhone X'] page.emulate(mobile) await page.waitFor(5000); }) after(async function(){ await browser.close() }) });