How to use setOfflineMode 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.

offline-test.js

Source: offline-test.js Github

copy
1const { expect } = require('chai');
2const visit = require('./helpers/visit');
3
4async function waitForAllServiceWorkers(page) {
5  return await page.evaluate(() => {
6    return navigator.serviceWorker.ready;
7  });
8}
9
10describe('when offline', function() {
11  it('the app loads on the index route', async function() {
12    await visit('/', async (page) => {
13      await waitForAllServiceWorkers(page);
14      await page.setOfflineMode(true);
15      await page.reload({ waitUntil: 'networkidle0' });
16
17      let element = await page.waitForSelector('[data-test-breethe]');
18
19      expect(element).to.be.ok;
20    });
21  });
22
23  it('the app loads on the search route', async function() {
24    await visit('/search/Salzburg', async (page) => {
25      await waitForAllServiceWorkers(page);
26      await page.setOfflineMode(true);
27      await page.reload({ waitUntil: 'networkidle0' });
28
29      let element = await page.waitForSelector('[data-test-breethe]');
30
31      expect(element).to.be.ok;
32    });
33  });
34
35  it('the app loads on the location route', async function() { 
36    await visit('/location/2', async (page) => {
37      await waitForAllServiceWorkers(page);
38      await page.setOfflineMode(true);
39      await page.reload();
40
41      let element = await page.waitForSelector('[data-test-measurement="PM10"] [data-test-measurement-value="15"]');
42
43      expect(element).to.be.ok;
44    });
45  });
46
47  it('disables the location search field', async function() {
48    await visit('/', async (page) => {
49      await page.setOfflineMode(true);
50
51      let element = await page.waitForSelector('[data-test-search-input]:disabled');
52
53      expect(element).to.be.ok;
54    });
55  });
56
57  it('disables the location search button', async function() {
58    await visit('/', async (page) => {
59      await page.setOfflineMode(true);
60
61      let element = await page.waitForSelector('[data-test-search-submit]:disabled');
62
63      expect(element).to.be.ok;
64    });
65  });
66
67  it('shows an offline warning on the index rotue', async function() {
68    await visit('/', async (page) => {
69      await page.setOfflineMode(true);
70
71      let element = await page.waitForSelector('[data-test-offline-warning]');
72
73      expect(element).to.be.ok;
74    });
75  });
76
77  it('shows an offline warning on the search rotue', async function() {
78    await visit('/search/Salzburg', async (page) => {
79      await page.setOfflineMode(true);
80
81      let element = await page.waitForSelector('[data-test-offline-warning]');
82
83      expect(element).to.be.ok;
84    });
85  });
86
87  it('does not show an offline warning on the location rotue', async function() {
88    await visit('/location/2', async (page) => {
89      await page.setOfflineMode(true);
90      await page.waitFor(100);
91
92      let element = await page.$('[data-test-offline-warning]');
93
94      expect(element).to.be.null;
95    });
96  });
97
98  it('the main user flow works', async function() {
99    await visit('/', async (page) => {
100      // go through the flow online first so we populate IndexedDB
101      await page.type('[data-test-search-input]', 'Salzburg');
102      await page.click('[data-test-search-submit]');
103      await page.waitForSelector('[data-test-search-result="Salzburg"]');
104      await page.click('[data-test-search-result="Salzburg"] a');
105      await page.waitForSelector('[data-test-measurement="PM10"] [data-test-measurement-value="15"]');
106      await page.click('[data-test-home-link]');
107      await page.waitForSelector('[data-test-search]');
108
109      await page.setOfflineMode(true);
110
111      // click the recent location
112      await page.waitForSelector('[data-test-search-result="Salzburg"]');
113      await page.click('[data-test-search-result="Salzburg"] a');
114      // check the correct data is still present
115      let element = await page.waitForSelector('[data-test-measurement="PM10"] [data-test-measurement-value="15"]');
116      expect(page.url()).to.match(/\/location\/2$/);
117
118      expect(element).to.be.ok;
119    });
120  });
121
122  describe('when coming back online', function() {
123    it('enables the location search field', async function() {
124      await visit('/', async (page) => {
125        await page.setOfflineMode(true); // go offline
126        await page.waitForSelector('[data-test-offline-warning]');
127        await page.setOfflineMode(false); // …and back online
128        await page.waitFor(100);
129
130        let element = await page.waitForSelector('[data-test-search-input]:enabled');
131
132        expect(element).to.be.ok;
133      });
134    });
135
136    it('enables the location search button', async function() {
137      await visit('/', async (page) => {
138        await page.setOfflineMode(true); // go offline
139        await page.waitForSelector('[data-test-offline-warning]');
140        await page.setOfflineMode(false); // …and back online
141        await page.waitFor(100);
142
143        let element = await page.waitForSelector('[data-test-search-submit]:enabled');
144
145        expect(element).to.be.ok;
146      });
147    });
148
149    it('hides the offline warning', async function() {
150      await visit('/', async (page) => {
151        await page.setOfflineMode(true); // go offline
152        await page.waitForSelector('[data-test-offline-warning]');
153        await page.setOfflineMode(false); // …and back online
154        await page.waitFor(10);
155
156        let element = await page.$('[data-test-offline-warning]');
157
158        expect(element).to.be.null;
159      });
160    });
161  });
162});
163
Full Screen

app.js

Source: app.js Github

copy
1// --------------------------------------------------
2// APP.JS
3// --------------------------------------------------
4
5//
6// Initialize Foundation
7// --------------------------------------------------
8
9$(document).foundation();
10
11//
12// Custom JS
13// --------------------------------------------------
14
15const setOfflineMode = function (status, connectionStatus = '') {
16    if (status === 'on') {
17        $('body').addClass('offline');
18    } else {
19        $('body').removeClass('offline');
20    }
21    if (connectionStatus === 'offline') {
22        $('body').addClass('no-connection');
23        $('#toggleOfflineMode').attr('disabled', true);
24    } else {
25        $('body').removeClass('no-connection');
26        $('#toggleOfflineMode').attr('disabled', false);
27    }
28}
29
30const openFullscreen = function () {
31    const elem = document.documentElement;
32    if (elem.requestFullscreen) {
33        elem.requestFullscreen();
34    } else if (elem.mozRequestFullScreen) { /* Firefox */
35        elem.mozRequestFullScreen();
36    } else if (elem.webkitRequestFullscreen) { /* Chrome, Safari and Opera */
37        elem.webkitRequestFullscreen();
38    } else if (elem.msRequestFullscreen) { /* IE/Edge */
39        elem.msRequestFullscreen();
40    }
41}
42
43const closeFullscreen = function () {
44    if (document.exitFullscreen) {
45        document.exitFullscreen();
46    } else if (document.mozCancelFullScreen) { /* Firefox */
47        document.mozCancelFullScreen();
48    } else if (document.webkitExitFullscreen) { /* Chrome, Safari and Opera */
49        document.webkitExitFullscreen();
50    } else if (document.msExitFullscreen) { /* IE/Edge */
51        document.msExitFullscreen();
52    }
53}
54
55const slickFadeout = function(center) {
56    const levels = [1, .5, .2];
57    center.css('opacity', levels[0]);
58    center.next().css('opacity', levels[1]);
59    center.next().next().css('opacity', levels[2]);
60    center.prev().css('opacity', levels[1]);
61    center.prev().prev().css('opacity', levels[2]);
62}
63
64const slickInit = function () {
65    let slickAutoplaySpeed = localStorage.getItem('slickAutoplaySpeed');
66    $('input.carouselTiming').val(slickAutoplaySpeed);
67    if (!slickAutoplaySpeed) {
68        slickAutoplaySpeed = 3000;
69    }
70
71    $('.carousel').slick({
72        centerMode: true,
73        centerPadding: '60px',
74        slidesToShow: 3,
75        autoplay: true,
76        autoplaySpeed: slickAutoplaySpeed,
77        swipe: false,
78    })
79    slickFadeout($('.slick-center'));
80}
81
82const loadCards = function () {
83    let cards = localStorage.getItem('cards');
84    if (cards) {
85        return JSON.parse(cards);
86    }
87    return false;
88}
89
90const saveCards = function (cards) {
91    if (cards) {
92        localStorage.setItem("cards", JSON.stringify(cards));
93    }
94}
95
96const restoreCards = function () {
97    let cards = loadCards();
98    if (!cards) {
99        $("input").prop("checked", true);
100        cards = getCheckedCards();
101    }
102    displayCards(cards);
103    $("input").prop("checked", false);
104    cards.forEach(cardId => {
105        $("input#check-" + cardId).prop("checked", true);
106    });
107}
108
109const getCheckedCards = function () {
110    let cards = [];
111    const checked = $(".available-cards input:checked");
112    checked.each(function() {
113        cards.push($(this).val())
114    });
115    return cards;
116}
117
118const displayCards = function (cards) {
119    $(".main .card").closest(".cell").hide();
120    cards.forEach(function(cardId) {
121        $(".cards-container #" + cardId).closest(".cell").show();
122    })
123}
124
125// check for online status
126if (navigator.onLine) {
127    setOfflineMode("off");
128} else {
129    setOfflineMode("on", "offline");
130}
131window.addEventListener('online', function () {
132    setOfflineMode("off");
133});
134window.addEventListener('offline', function () {
135    setOfflineMode("on", "offline");
136});
137
138// set up the Slick carousel
139$(document).ready(function () {
140
141    restoreCards();
142
143    // restore screensaver
144    const screensaverPoster = localStorage.getItem('screensaverPoster');
145    const screensaverSrc = localStorage.getItem('screensaverSrc');
146    if (screensaverPoster) {
147        $('.screensaver video').attr('poster', screensaverPoster);
148    }
149    $('.screensaver video').attr('src', screensaverSrc);
150    $(`input.screensaver-select[data-src='${screensaverSrc}']`).prop('checked', true);
151
152    $(".available-cards input").on("change", function() {
153        let cards = getCheckedCards();
154        displayCards(cards);
155        saveCards(cards);
156    })
157
158    slickInit();
159
160    $('input.carouselTiming').on("change", function() {
161        localStorage.setItem("slickAutoplaySpeed", $(this).val());
162        $("button.browserRefresh").show();
163    })
164
165    $("button.browserRefresh").on("click", function() {
166        window.location.reload(true);
167    })
168
169    $('.carousel').on('beforeChange', function() {
170        slickFadeout($('.slick-center').next());
171    })
172
173    $(document).on('open.zf.reveal', function () {
174        $('.carousel').slick('slickPause');
175    }).on('closed.zf.reveal', function () {
176        $('.carousel').slick('slickPlay');
177        $('video').trigger('pause');
178    })
179
180    $('#toggleFullScreen').on('click', function () {
181        if ($(this).is(":checked")) {
182            openFullscreen();
183        } else {
184            closeFullscreen();
185        }
186    })
187
188    $('#toggleOfflineMode').on('click', function () {
189        if (!navigator.onLine) { return }
190        if ($("body").hasClass("offline")) {
191            setOfflineMode("off");
192        } else {
193            setOfflineMode("on");
194        }
195    })
196
197    $('#toggleScreensaver').on('click', function () {
198        if ($("body").hasClass("screensaver-on")) {
199            $("body").removeClass("screensaver-on");
200            $('.carousel').slick('slickPlay');
201        } else {
202            $("body").addClass("screensaver-on");
203            $('.carousel').slick('slickPause');
204        }
205    })
206
207    $('input.screensaver-select').on('click', function () {
208        const src = $(this).data('src');
209        const poster = $(this).data('poster');
210        if (poster) {
211            $('.screensaver video').attr('poster', poster);
212            localStorage.setItem('screensaverPoster', poster);
213        }
214        $('.screensaver video').attr('src', src);
215        localStorage.setItem('screensaverSrc', src);
216    })
217
218})
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)