How to use emulateMediaFeatures method in Puppeteer

Best JavaScript code snippet using puppeteer

Run Puppeteer automation tests on LambdaTest cloud grid

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

Storyshots.spec.js

Source: Storyshots.spec.js Github

copy
1import initStoryshots from '@storybook/addon-storyshots';
2import { axeTest, imageSnapshot } from '@storybook/addon-storyshots-puppeteer';
3
4
5describe('axe A11Y Storyshots [LIGHT]', () => {
6    initStoryshots({
7        suite: 'A11Y',
8        test: axeTest({
9            storybookUrl: 'http://localhost:6006/',
10            customizePage: (page) => {
11                page.emulateMediaFeatures([{
12                    name: 'prefers-color-scheme',
13                    value: 'light'
14                }])
15            }
16        }),
17    });
18})
19
20describe('axe A11Y Storyshots [DARK]', () => {
21    initStoryshots({
22        suite: 'A11Y',
23        test: axeTest({
24            storybookUrl: 'http://localhost:6006/',
25            customizePage: (page) => {
26                page.emulateMediaFeatures([{
27                    name: 'prefers-color-scheme',
28                    value: 'dark'
29                }])
30            }
31        }),
32    });
33})
34
35
36describe('Image Snapshots [LIGHT]', () => {
37    initStoryshots({
38        suite: 'Image Snapshots [LIGHT]',
39        test: imageSnapshot({
40
41            customizePage: (page) => {
42                page.emulateMediaFeatures([{
43                    name: 'prefers-color-scheme',
44                    value: 'light'
45                }])
46            },
47            beforeScreenshot: async (page) => {
48                await page.waitForSelector('.page-element');
49                await page.$$eval(
50                    'img',
51                    images => {
52                        images.forEach(img => {
53                            img.removeAttribute('src');
54                        })
55                    }
56                );
57            },
58
59            // 🤷‍♂️
60            // storyKindRegex: /^((?!.*?Loader).)*$/,
61
62            // 🤷‍♂️
63            // getMatchOptions: ({ context: { kind, story}, device, viewport }) => ({
64            //     customSnapshotIdentifier:
65            //         (device ? `${ device.name }-` : '') +
66            //         (viewport ? `${ viewport.width }X${ viewport.height }-` : '') +
67            //         `${ kind }-${ story }`
68            //             .toLowerCase()
69            // }),
70        })
71    });
72})
73
74describe('Image Snapshots [DARK] [800x600]', () => {
75    initStoryshots({
76        suite: 'Image Snapshots [DARK] [800x600]',
77        test: imageSnapshot({
78            customizePage: async (page) => {
79                await page.emulateMediaFeatures([{
80                    name: 'prefers-color-scheme',
81                    value: 'dark'
82                }])
83            },
84            beforeScreenshot: async (page) => {
85                await page.waitForSelector('.page-element');
86                await page.$$eval(
87                    'img',
88                    images => {
89                        images.forEach(img => {
90                            img.removeAttribute('src');
91                        })
92                    }
93                );
94            }
95        })
96    });
97})
98
99describe('Image Snapshots [DARK] [DESKTOP]', () => {
100    initStoryshots({
101        suite: 'Image Snapshots [DARK] [DESKTOP]',
102        test: imageSnapshot({
103            customizePage: async (page) => {
104                await page.emulateMediaFeatures([{
105                    name: 'prefers-color-scheme',
106                    value: 'dark'
107                }])
108                await page.setViewport({
109                    width: 1280,
110                    height: 800,
111                    isMobile: false
112                });
113            },
114            beforeScreenshot: async (page) => {
115                await page.waitForSelector('.page-element');
116                await page.$$eval(
117                    'img',
118                    images => {
119                        images.forEach(img => {
120                            img.removeAttribute('src');
121                        })
122                    }
123                );
124            }
125        })
126    });
127})
128
129describe('Image Snapshots [DARK] [MOBILE]', () => {
130    initStoryshots({
131        suite: 'Image Snapshots [DARK] [MOBILE]',
132        test: imageSnapshot({
133            customizePage: async (page) => {
134                await page.emulateMediaFeatures([{
135                    name: 'prefers-color-scheme',
136                    value: 'dark'
137                }])
138
139                await page.setViewport({
140                    width: 375,
141                    height: 812,
142                    deviceScaleFactor: 1,
143                    isMobile: true,
144                    hasTouch: true,
145                    isLandscape: false
146                });
147            },
148            beforeScreenshot: async (page) => {
149                await page.waitForSelector('.page-element');
150                await page.$$eval(
151                    'img',
152                    images => {
153                        images.forEach(img => {
154                            img.removeAttribute('src');
155                        })
156                    }
157                );
158            }
159        })
160    });
161})
162
163
164
Full Screen

emulation.spec.js

Source: emulation.spec.js Github

copy
1/**
2 * Copyright 2018 Google Inc. All rights reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17module.exports.addTests = function({testRunner, expect, puppeteer}) {
18  const {describe, xdescribe, fdescribe, describe_fails_ffox} = testRunner;
19  const {it, fit, xit, it_fails_ffox} = testRunner;
20  const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
21
22  const iPhone = puppeteer.devices['iPhone 6'];
23  const iPhoneLandscape = puppeteer.devices['iPhone 6 landscape'];
24
25  describe('Page.viewport', function() {
26    it('should get the proper viewport size', async({page, server}) => {
27      expect(page.viewport()).toEqual({width: 800, height: 600});
28      await page.setViewport({width: 123, height: 456});
29      expect(page.viewport()).toEqual({width: 123, height: 456});
30    });
31    it('should support mobile emulation', async({page, server}) => {
32      await page.goto(server.PREFIX + '/mobile.html');
33      expect(await page.evaluate(() => window.innerWidth)).toBe(800);
34      await page.setViewport(iPhone.viewport);
35      expect(await page.evaluate(() => window.innerWidth)).toBe(375);
36      await page.setViewport({width: 400, height: 300});
37      expect(await page.evaluate(() => window.innerWidth)).toBe(400);
38    });
39    it('should support touch emulation', async({page, server}) => {
40      await page.goto(server.PREFIX + '/mobile.html');
41      expect(await page.evaluate(() => 'ontouchstart' in window)).toBe(false);
42      await page.setViewport(iPhone.viewport);
43      expect(await page.evaluate(() => 'ontouchstart' in window)).toBe(true);
44      expect(await page.evaluate(dispatchTouch)).toBe('Received touch');
45      await page.setViewport({width: 100, height: 100});
46      expect(await page.evaluate(() => 'ontouchstart' in window)).toBe(false);
47
48      function dispatchTouch() {
49        let fulfill;
50        const promise = new Promise(x => fulfill = x);
51        window.ontouchstart = function(e) {
52          fulfill('Received touch');
53        };
54        window.dispatchEvent(new Event('touchstart'));
55
56        fulfill('Did not receive touch');
57
58        return promise;
59      }
60    });
61    it('should be detectable by Modernizr', async({page, server}) => {
62      await page.goto(server.PREFIX + '/detect-touch.html');
63      expect(await page.evaluate(() => document.body.textContent.trim())).toBe('NO');
64      await page.setViewport(iPhone.viewport);
65      await page.goto(server.PREFIX + '/detect-touch.html');
66      expect(await page.evaluate(() => document.body.textContent.trim())).toBe('YES');
67    });
68    it('should detect touch when applying viewport with touches', async({page, server}) => {
69      await page.setViewport({ width: 800, height: 600, hasTouch: true });
70      await page.addScriptTag({url: server.PREFIX + '/modernizr.js'});
71      expect(await page.evaluate(() => Modernizr.touchevents)).toBe(true);
72    });
73    it('should support landscape emulation', async({page, server}) => {
74      await page.goto(server.PREFIX + '/mobile.html');
75      expect(await page.evaluate(() => screen.orientation.type)).toBe('portrait-primary');
76      await page.setViewport(iPhoneLandscape.viewport);
77      expect(await page.evaluate(() => screen.orientation.type)).toBe('landscape-primary');
78      await page.setViewport({width: 100, height: 100});
79      expect(await page.evaluate(() => screen.orientation.type)).toBe('portrait-primary');
80    });
81  });
82
83  describe('Page.emulate', function() {
84    it('should work', async({page, server}) => {
85      await page.goto(server.PREFIX + '/mobile.html');
86      await page.emulate(iPhone);
87      expect(await page.evaluate(() => window.innerWidth)).toBe(375);
88      expect(await page.evaluate(() => navigator.userAgent)).toContain('iPhone');
89    });
90    it('should support clicking', async({page, server}) => {
91      await page.emulate(iPhone);
92      await page.goto(server.PREFIX + '/input/button.html');
93      const button = await page.$('button');
94      await page.evaluate(button => button.style.marginTop = '200px', button);
95      await button.click();
96      expect(await page.evaluate(() => result)).toBe('Clicked');
97    });
98  });
99
100  describe('Page.emulateMedia', function() {
101    it('should be an alias for Page.emulateMediaType', async({page, server}) => {
102      expect(page.emulateMedia).toEqual(page.emulateMediaType);
103    });
104  });
105
106  describe('Page.emulateMediaType', function() {
107    it('should work', async({page, server}) => {
108      expect(await page.evaluate(() => matchMedia('screen').matches)).toBe(true);
109      expect(await page.evaluate(() => matchMedia('print').matches)).toBe(false);
110      await page.emulateMediaType('print');
111      expect(await page.evaluate(() => matchMedia('screen').matches)).toBe(false);
112      expect(await page.evaluate(() => matchMedia('print').matches)).toBe(true);
113      await page.emulateMediaType(null);
114      expect(await page.evaluate(() => matchMedia('screen').matches)).toBe(true);
115      expect(await page.evaluate(() => matchMedia('print').matches)).toBe(false);
116    });
117    it('should throw in case of bad argument', async({page, server}) => {
118      let error = null;
119      await page.emulateMediaType('bad').catch(e => error = e);
120      expect(error.message).toBe('Unsupported media type: bad');
121    });
122  });
123
124  describe_fails_ffox('Page.emulateMediaFeatures', function() {
125    it('should work', async({page, server}) => {
126      await page.emulateMediaFeatures([
127        { name: 'prefers-reduced-motion', value: 'reduce' },
128      ]);
129      expect(await page.evaluate(() => matchMedia('(prefers-reduced-motion: reduce)').matches)).toBe(true);
130      expect(await page.evaluate(() => matchMedia('(prefers-reduced-motion: no-preference)').matches)).toBe(false);
131      await page.emulateMediaFeatures([
132        { name: 'prefers-color-scheme', value: 'light' },
133      ]);
134      expect(await page.evaluate(() => matchMedia('(prefers-color-scheme: light)').matches)).toBe(true);
135      expect(await page.evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches)).toBe(false);
136      expect(await page.evaluate(() => matchMedia('(prefers-color-scheme: no-preference)').matches)).toBe(false);
137      await page.emulateMediaFeatures([
138        { name: 'prefers-color-scheme', value: 'dark' },
139      ]);
140      expect(await page.evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches)).toBe(true);
141      expect(await page.evaluate(() => matchMedia('(prefers-color-scheme: light)').matches)).toBe(false);
142      expect(await page.evaluate(() => matchMedia('(prefers-color-scheme: no-preference)').matches)).toBe(false);
143      await page.emulateMediaFeatures([
144        { name: 'prefers-reduced-motion', value: 'reduce' },
145        { name: 'prefers-color-scheme', value: 'light' },
146      ]);
147      expect(await page.evaluate(() => matchMedia('(prefers-reduced-motion: reduce)').matches)).toBe(true);
148      expect(await page.evaluate(() => matchMedia('(prefers-reduced-motion: no-preference)').matches)).toBe(false);
149      expect(await page.evaluate(() => matchMedia('(prefers-color-scheme: light)').matches)).toBe(true);
150      expect(await page.evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches)).toBe(false);
151      expect(await page.evaluate(() => matchMedia('(prefers-color-scheme: no-preference)').matches)).toBe(false);
152    });
153    it('should throw in case of bad argument', async({page, server}) => {
154      let error = null;
155      await page.emulateMediaFeatures([{ name: 'bad', value: '' }]).catch(e => error = e);
156      expect(error.message).toBe('Unsupported media feature: bad');
157    });
158  });
159
160  describe_fails_ffox('Page.emulateTimezone', function() {
161    it('should work', async({page, server}) => {
162      page.evaluate(() => {
163        globalThis.date = new Date(1479579154987);
164      });
165      await page.emulateTimezone('America/Jamaica');
166      expect(await page.evaluate(() => date.toString())).toBe('Sat Nov 19 2016 13:12:34 GMT-0500 (Eastern Standard Time)');
167
168      await page.emulateTimezone('Pacific/Honolulu');
169      expect(await page.evaluate(() => date.toString())).toBe('Sat Nov 19 2016 08:12:34 GMT-1000 (Hawaii-Aleutian Standard Time)');
170
171      await page.emulateTimezone('America/Buenos_Aires');
172      expect(await page.evaluate(() => date.toString())).toBe('Sat Nov 19 2016 15:12:34 GMT-0300 (Argentina Standard Time)');
173
174      await page.emulateTimezone('Europe/Berlin');
175      expect(await page.evaluate(() => date.toString())).toBe('Sat Nov 19 2016 19:12:34 GMT+0100 (Central European Standard Time)');
176    });
177
178    it('should throw for invalid timezone IDs', async({page, server}) => {
179      let error = null;
180      await page.emulateTimezone('Foo/Bar').catch(e => error = e);
181      expect(error.message).toBe('Invalid timezone ID: Foo/Bar');
182      await page.emulateTimezone('Baz/Qux').catch(e => error = e);
183      expect(error.message).toBe('Invalid timezone ID: Baz/Qux');
184    });
185  });
186
187};
188
Full Screen

dark-mode.js

Source: dark-mode.js Github

copy
1const puppeteer = require('puppeteer');
2
3(async () => {
4  const browser = await puppeteer.launch();
5
6  const page = await browser.newPage();
7
8  await page.goto('https://googlechromelabs.github.io/dark-mode-toggle/demo/index.html');
9  await page.emulateMediaFeatures([{ name: 'prefers-color-scheme', value: 'light' }]);
10  await page.waitFor(200);
11  await page.screenshot({ path: 'light.jpg', type: 'jpeg', omitBackground: true });
12  await page.emulateMediaFeatures([{ name: 'prefers-color-scheme', value: 'dark' }]);
13  await page.waitFor(200);
14  await page.screenshot({ path: 'dark.jpg', type: 'jpeg', omitBackground: true });
15  await browser.close();
16})();
17
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Puppeteer on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)