-
Notifications
You must be signed in to change notification settings - Fork 3.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Simulate offline mode #235
Comments
This should be possible to do, but it's not immediately obvious or easy. Thoughts / Concerns
I'll move this into our Roadmap for further research. |
With Chrome 63 coming out we will be able to support the debugger protocol. #832 |
Good onya guys. I'm ready for this right now. You know what to do. |
Is there any progress/news on this? Would be cool to be able to test PWAs 👍 |
No progress on this unfortunately. |
I am using Redux and we store the online/offline status of the browser there. So what we did was to expose the Redux store like this in eg index.js (only works on localhost): if (window.Cypress) {
window.store = store
} Then in a test in cypress we dispatched an action to set the Redux state to be offline: cy.window().its('store')
.then(
store => store.dispatch({type: 'OFFLINE', status: true})
); |
Guys it's 2019 👀 |
This comment has been minimized.
This comment has been minimized.
Related issue for clearing ServiceWorkers: #702 @lolpez We prioritize issues we work on based on a variety of factors - including the number of users requesting/helped by a feature. While this is still on our Roadmap, many other features are a higher priority today as a result of this assessment. Sorry for the delay. |
I tried to simulate offline by setting up a reverse proxy to my running server and then shutting it down. const httpProxy = require("http-proxy");
context("Offline", () => {
before(() => {
httpProxy.createProxyServer({ target: "http://localhost:9000" }).listen(9001);
cy.log("Open / on proxy");
cy.visit("http://localhost:9001/");
});
it("should show update notification", () => {
// wait for initial service worker installation
cy.wait(3000);
// stop the proxy server
proxy.close();
// reload the page
cy.reload();
});
}); But I get a If I run just these two files in a separate file there is no problem const httpProxy = require("http-proxy");
httpProxy.createProxyServer({ target: "http://localhost:9000" }).listen(9001); Is this a known limitation / problem? |
It would be really good to have this feature. I can currently set the offline state in our vuex store but when changing pages (ie cy.visit) the application rechecks the state and updates the store value and is flushing queues before I get a chance to set the store again! |
Absence of this feature actually forces us to use selenium with direct access to driver api so we can test our core functionality in offline mode as our use case is offline-first. I hope you will find time soon for this. |
The project my team is working on requires that we are able to simulate a No Internet Connection environment as well. Please provide an update on this! |
hello, any updates on this? |
This issue is still in the 'proposal' stage, which means no work has been done on this issue as of today, so we do not have an estimate on when this will be delivered. |
One way of simulating offline mode: cy.server({ force404: true }); // offline mode
cy.server({ enable: false}); // online mode |
that only blocks the calls, it doesn't tell the browser there's no internet |
Yes, it doesn't tell the browser that there is no internet, but by preventing the requests, we can test the offline functionality of PWA. It's just a workaround. |
In my case it doesn't help, it should appear a "offline" banner and it doesn't. |
The root of the app is not cachable because of the MITM that Cypress performs (`document.domain = 'localhost'). This would make it (at least to me) that one would enable offline-mode after having started testing. First you'd want to install your service worker and such, adding all required files to the cache, and then run some tests. This would mean a global option is not required/desired - if you have no cache, no prior visits to the site - offline will never work anyways. Design// Quick and dirty
cy.offline()
// - do tests inbetween
cy.online()
// A probably better way:
cy.network({offline: true})
// - do tests inbetween
cy.network({offline: false]) The latter would enable Cypress to at at later point also add throttling in the options. Not sure as to the usefulness of throttling, but that's point of discussion for another issue. DocsThe Chrome Debugger (Chrome, Electron) allows for the following, but Firefox does not. Cypress.automation('remote:debugger:protocol', {
command: 'Network.enable',
})
Cypress.automation('remote:debugger:protocol', {
command: 'Network.emulateNetworkConditions',
params: {
offline: options.offline,
'latency': 0,
'downloadThroughput': 0,
'uploadThroughput': 0,
'connectionType': 'none',
},
}) Hurdles
Half-way through my test (within a single UpdateI've created a PR, but I'm not making any progress on Firefox. According to this issue Firefox does not seem to implement The Firefox UI has a Update 2Unless we figure out how to automate it for Firefox, the chances of any PR making it into Cypress are slim to none. Call to everyone: feel free to try and find a way ;-). Update 3Work on the |
For documentation: The debugger protocol approach as described on the blog doesn't work since 7.3.0. This is probably the cause. |
I have implemented the following but nothing seems to work. Code can be seen below.
export class NetworkConnectivity {
private static readonly affectedUrlsRegex = /(?<=localhost:\d+)\/(apollo|api)\/.+$/g
public static goOffline () {
const offlineDevtoolCommand = {
command: 'Network.emulateNetworkConditions',
params: {
offline: true,
latency: -1,
downloadThroughput: -1,
uploadThroughput: -1
}
}
return cy
.then(() => Cypress.automation('remote:debugger:protocol', { command: 'Network.enable' }))
.then(() => cy.task('sendCommandsToServiceWorker', { command: 'Network.enable' }))
.then(() => cy.task('sendCommandsToServiceWorker', offlineDevtoolCommand, { timeout: 120000 }))
.then(() => Cypress.automation('remote:debugger:protocol', offlineDevtoolCommand))
.then(() => {
// Reference: https://docs.cypress.io/api/commands/intercept#Controlling-the-response
// @ts-ignore
Cypress.config('network', { isOnline: false })
cy.intercept(this.affectedUrlsRegex, req => {
// @ts-ignore
const { isOnline } = Cypress.config('network')
if (!isOnline) {
req.destroy()
}
})
})
} Both of these would not entirely intercept the request and the request would still return a 200 response. This might be because we are using service workers. To try and fix this issue, I tried using const puppeteer = require('puppeteer-core')
const REMOTE_DEBUGGING_PORT = 9222
async function sendCommandsToServiceWorker ({ command, params }) {
console.log(`Plugin started executing command ${command}, params: `, params)
const browser = await puppeteer.connect({ browserURL: `http://localhost:${REMOTE_DEBUGGING_PORT}` })
const targets = await browser.targets()
const serviceWorkers = targets.filter((t) => t.type() === 'service_worker' || t.type() === 'other')
const sendPromises = serviceWorkers.map(async (serviceWorker) => {
const cdpSession = await serviceWorker.createCDPSession()
await cdpSession.send(command, params)
})
await Promise.all(sendPromises)
return null
}
module.exports = {
sendCommandsToServiceWorker
} Here is the screenshot of the CI/CD error. I would really appreciate if anyone has solved this issue or have a workaround when using service workers. |
Guys it's 2022 👀 |
This worked for me cy.log('go offline'); |
Copy exactly same from above and try again |
I tried, but it still does not work on Chrome when I am trying to get back online, it only works on Electron. I also tried the solution posted in here, but without success:
|
your code is missing return, premise returning nothing, try this cy.log('go offline'); |
I managed to get it offline, but the problem is to put it back online, in which it is working well only on Electron. |
Downgraded Cypress to 7.2.0. Seems to work. UPD |
Same problem: 7.9.0 version. |
I observe this problem in 10+ version in Electron runner as well. |
This one works for me const goOffline = () => { |
I'm facing this problem too. I'm using this code below: network(params) {
cy.log(`**Offline: ${params.offline}**`)
.then(() => {
Cypress.automation('remote:debugger:protocol', {
command: 'Network.enable',
});
})
.then(() => {
Cypress.automation('remote:debugger:protocol', {
command: 'Network.emulateNetworkConditions',
params: {
offline: params.offline,
latency: 0,
downloadThroughput: 0,
uploadThroughput: 0,
connectionType: 'none',
},
});
});
}, I've work with cypress 9.5.1. After going offline, can't get back online. Anyone has a solution for this? |
Cypress v10.3.1 and still the same issue with going back Online. |
Hello everyone I have been stuck into this issue for at least 2 weeks ago and i got a "solution" to try simulate offline mode. The code is in the image below Create this function on custom commands file of your project and call it using "cy.network({online: false})" I'm using cypress 9.5.1 |
Guys it's 2023 👀 |
laerteneto |
Modifying the real // go offline
cy.window().then((win) => {
cy.stub(win.navigator, 'onLine').value(false);
cy.wrap(win).trigger('offline');
});
// go online
cy.window().then((win) => {
cy.stub(win.navigator, 'onLine').value(true);
cy.wrap(win).trigger('online');
}); |
@laerteneto did you get any solution? Im stuck with go online too |
Confirming the workability of this solution. Cypress v10, Chrome 117 (only in headless). Don't forget to put go online into before, beforeEach and afterEach |
Guys it's 2024 👀 |
I'm using this for Cypress 13.11.0 and Chrome v126: https://www.cypress.io/blog/2020/11/12/testing-application-in-offline-network-mode |
8 years later.... I did exactly what it's in this article, but the problem is that all tests after |
Description
Offline support is becoming important to web applications. It would be nice to switch the browser to the offline mode from Cypress either by test or for all tests and run it. If might be difficult and might require Cypress to handle ServiceWorkers very well.
Additional Info
The text was updated successfully, but these errors were encountered: