-
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
Unable to switch userAgent during test run #2100
Comments
Verified.
describe('A certain page', () => {
before(() => {
console.log(Cypress.config('userAgent' as any)); // outputs: null
Cypress.config('userAgent' as any, 'mobile_value'); // set userAgent
console.log(Cypress.config('userAgent' as any)); //outputs: mobile_value
});
it('should exhibit mobile behaviour', () => {
console.log(navigator.userAgent); // Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36
});
});
describe('A certain page', () => {
before(() => {
console.log(Cypress.config('userAgent' as any)); // outputs: testValue
Cypress.config('userAgent' as any, 'mobile_value'); // set userAgent
console.log(Cypress.config('userAgent' as any)); //outputs: mobile_value
});
it('should exhibit mobile behaviour', () => {
console.log(navigator.userAgent); // testValue
});
}); |
Cypress version: 3.1.0 I'm experiencing what seems to be the same behavior as @hdjong1. If I log the |
You cannot change the user agent in the middle of a test. What you can do is split up the mobile tests from the desktop tests and then run those groups separately via a different The only way for us to be able to change the userAgent on the fly is at the network layer. We could make that work but that's really more applicable to the network stubbing rewrite. |
@brian-mann Thanks for the quick reply and suggestion! Is this limitation unique to setting the |
Its a limitation that exists for a few different config values - basically anything that's not directly under Cypress's control like things such as timeouts or environment variables, etc.
|
I don't see this mentioned in the Thanks for your help! |
It's been talked about in other issues - and I think the general consensus was to freeze or lock properties that cannot be changed so that it would throw and you'd immediately know. |
Makes sense. That would be much quicker than consulting documentation, which would be convenient. Next time it comes up you can mention the random guy in issue #2100 who supports the freeze/lock and throw idea if you need a tie breaker. In fact, popup my profile pic when it throws with the caption "No." |
So I see above that there might be a way to run I'm getting a huge error in the UI when I attempt to run that. |
@nobleach The value you're specifying for
In the plugins export, if "mobile" is specified, then I add the full user agent string to the config that gets returned if (config.env.userAgent === 'mobile') {
data.userAgent =
'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A356 Safari/604.1';
} It doesn't feel very pretty, but the user agent needs to be specified before Cypress loads the config and this is what I came up with. |
I suppose that's viable. I'm interested in how others handle it too. An adaptive app that renders a different experience for mobile/tablet/desktop isn't that far outside of reality, is it? I very much appreciate you sharing your approach, so thank you! |
I've been migrating my tests to Cypress and I'm facing this issue where we have 3 platforms and each needs a different user agent among other specific configurations that are caught and injected in our plugin, the same spec is run for each platform, so we do a loop before starting each spec suite. We have a fixture organized by platform, so we can assert easily. Doing it manually is not a viable solution, I thought I could also move away from gulp and just use npm run scripts, but so far the only way I could accomplish this is to have all the different configs in gulp. Is there any other approach you can suggest us? Thanks |
Using npm scripts shouldn't be a problem. We do it like this: "cypress:prod": "CYPRESS_baseUrl=http://localhost:8080 cypress run --env userAgent=mobile",
"cypress:prod:tablet": "CYPRESS_baseUrl=http://localhost:8080 cypress run --env userAgent=tablet",
"cypress:ci": "cypress:prod && cypress:prod:tablet", I've used the above suggestion in my module.exports = (on, config) => {
// create new config settings
const configOverride = {};
if (config.env.userAgent === 'mobile') {
configOverride.userAgent = 'Mozilla/5.0 (Linux; Android 6.0.1; SM-G532G Build/MMB29T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.83 Mobile Safari/537.36';
configOverride.testFiles = 'mobile/**/*.*';
} else if (config.env.userAgent === 'tablet') {
configOverride.userAgent = 'Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10';
configOverride.testFiles = 'tablet/**/*.*';
} else {
configOverride.userAgent = 'none';
}
return Object.assign({}, config, configOverride);
}; |
It would be nice if this can be mentioned in the online docs, it took me a while before figuring out what was wrong |
Another bump for clearer documentation on this (or some alert in the UI). It also took me some time to get here and figure out that this isn't possible. |
And another bump from me. I'm a paying customer and I wasted several hours till I was directed by someone to this issue. Issue was reported al,ost a year ago. If you can't change the functionality to match the docs then please change the docs to match the functionality. ---> PR here: cypress-io/cypress-documentation#1681 |
Related issue that would make it an error to try to use |
Added a note to config.md re: some values cannot be changed at run-time. Details based on @brian-mann 's comments to cypress-io/cypress#2100
Added a note to config.md re: some values cannot be changed at run-time. Details based on @brian-mann 's comments to cypress-io/cypress#2100
…me. (#1681) * Update config.md Added a note to config.md re: some values cannot be changed at run-time. Details based on @brian-mann 's comments to cypress-io/cypress#2100 * minor editing - fix url to urlHash * Fix urlHash reference Co-authored-by: Jennifer Shehane <[email protected]>
Can't test this on cypress due to cypress-io/cypress#2100
* Start on database changes * sketch out use cases * Add story with user meta (And migration for tests, this may update later) * Add story_li macro to me.html * Add hide policies * Start on story hide views * Fix database * Keep query params on hide/unhide action * black formatter * Use opacity instead of visibility for a11y * Add styling to view preferences * Add simple cypress test * Don't use opacity on mobile views Can't test this on cypress due to cypress-io/cypress#2100 * black formatter
Here is another workaround mentioned here, may be useful in some case: before(() => {
cy.visit(url, {
onBeforeLoad: win => {
Object.defineProperty(win.navigator, 'userAgent', {
value: 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
});
},
});
}); |
I was trying to use this method to trigger my React frontend to render the mobile page, but it didn't work. Any idea? |
Maybe you should also change the viewport size, such as |
same problem for us / annoying not to find this in the official docs but within the issues. fixed with @luokuning 's solution - thanks a lot |
I'd like to chime in my + 1. This is a must have feature 😬 I also lost one good hour trying to figure out why neither the second argument for I finally found this issue (and, to be fair, this on the documentation, stating that userAgent would be ignored), but a much better developer experience would to be thrown an error about this, warning that you were trying to change an immutable value during the test run. It's also confusing in the documentation that if you pass Regarding workarounds, I managed to set my user agent doing it like this: cy.visit('/my-url', {
headers: { 'user-agent': 'mobile' }
}); However, unfortunately that still doesn't cut it for our tests because it will send that header only in the first request, but not honor it on any page redirects; so if your test clicks on a button and gets redirected to another page, the redirect won't have those headers. Had I known this beforehand, I wouldn't have switched our test suite to Cypress. It's really a big deal for us because we use things like The other workaround posted here by @luokuning unfortunately doesn't work in Cypress 6. |
@feliperaul @jennifer-shehane any updated recommendations on persisting that user agent header throughout the whole test run? |
On Config I have nothing set as userAgent On my tests I have:
Still, I don't get iPad userAgent. I get the desktop one. I don't know what else to try. |
I don't think will work. This will set the user agent on the browser where the Test Runner is running, no where you visit your app. |
There MUST be a dynamic way to set the user agent rather than thru a command line for each userAgent, isn't it? None of the workarounds mentioned above that uses plugin/index worked for me (maybe I am doing something wrong, of course)... but isn't over there any clear documentation on how to dynamically (based on spec name, relative path, something like this) set a user agent before the run starts? I am also an enterprise client and this little thing is killing me (I love you tool, but there must be something over there that I am not fully catching) 🙏 |
I have used the approached that @luokuning mentioned, but it only seems to be working with the url I have passed with command, for instance, if I navigate to a different screen by clicking on a button or link, I lose the header object and the functionality returns to desktop view. |
Any changes in this scenario? or should I go with the split tests approach? |
I am unable to change/override userAgent via config file.
my plugins/index.js
The error is: Error: You must pass a valid event name when registering a plugin. I totally get it, I am unable to change it during runtime, but before that via config should work. What did I miss? |
@brobee Try taking a look at the pluginsFile configuration setup here: https://docs.cypress.io/guides/references/configuration#Plugins You should be able to slim this down set it up when the plugin is resolved: // cypress/plugins/index.js
+ module.exports = (on, config) => {
- on(config => {
if (config.env.platform === 'desktop') {
config.userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.109 Safari/537.36'
} else if (config.env.platform === 'mobile') {
config.userAgent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1'
}
return config
- })
}
|
@emilyrohrbough I tried this way without event, but it seems this particular code did not run and userAgent is still null. Is it possible to override the null? it seems weird to me |
No news on this? No workaround? Sorry to be the one that ask this question but it seems Cypress team is not updating, only users are. |
My workaround was to have a separated config file and manually running the tests for desktop and mobile. I know, it sucks but someone might find this useful. I have my regular configuration with all my options on the root folder called
So on my project
Hope it helps someone. |
This workaround does not work any more on Cypress 10. Any update on this ticket? Or What could I do on Cypress 10 if I need to switch userAgent during test run? Thanks |
It works for me. This configfile is for the cypress v10 and the file const { defineConfig } = require('cypress');
module.exports = defineConfig({
e2e: {
baseUrl: 'http://localhost:3000',
supportFile: 'cypress/support/e2e.js',
specPattern: 'cypress/integration/my-tests-folder/**/*',
userAgent:
'Mozilla/5.0 (Linux; U; Android 4.4.2; en-us; SCH-I535 Build/KOT49H) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
pageLoadTimeout: 70000,
},
}); |
There are more issues/discussions related to userAgent: https://github.com/cypress-io/cypress/discussions?discussions_q=userAgent, #4402, #9319 . As I saw in here:
Cypress just picks up the same userAgent configuration for every browser. I have an issue with a 3rd party library (tesseract) not working when "Electron" was in the userAgent string. So I removed it. I wonder why the same userAgent-String is forced by Cypress onto the browser and in case of Firefox they are even not realistic: Cypress Firefox: I'd suggest that it's probably a better way to set the userAgent for each browser correctly the first time (IMO Firefox is just wrong?) or allow the user agent to be set via cypress.config.js based on the browser:
The other workaround would be to extend browser configuration in 'before:browser:launch' launchOptions.preferences['general.useragent.override'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101 Firefox/91.0'; But this way we just override what Cypress is already overriding.. which seems cumbersome. PS. I thinka a lot of people would profit from such quality of life enhancements. |
we figured out how to fix it for Cypress 10 and basically 11
that should help but the problem that was solved for us in Cypress 10 with
how can we allow using |
@rnovosad since the super domains are the same same, are you able to just perform the visit without using cy.visit(url, {
onBeforeLoad: win => {
Object.defineProperty(win.navigator, 'userAgent', {
value: 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
});
},
});
cy.visit(`/${path}`, {
onBeforeLoad: (win) => {
Object.defineProperty(win.navigator, "userAgent", {
value:
"Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1"
});
}
}); |
@AtofStryker tried this, but it doesn't help... |
in other words the user agent fails to update? |
Current behavior:
I'm testing an application that, as many these days, has a responsive design. Based on the viewport the layout changes. However, for some parts, it's also important that the user agent is set to mobile in order to trigger certain functionality. Cypress provides an
userAgent
option incypress.json
which can be used for this.Since my test suite contains tests for both desktop and mobile scenario's I would like to set the
userAgent
option during test runs. By default, I just leave it empty which takes care of the desktop scenarios. When a mobile scenario is run I wantuserAgent
to be set to a mobile one, and switch back once a desktop scenario is encountered again. I'm usingCypress.config('userAgent', 'value')
in my spec files in order to do so.Steps to reproduce:
Test code:
Based on the above code I would expect to get the mobile version of my app served, but I'm still getting the desktop version through a mobile viewport. When I set the userAgent in
cypress.json
directly everything does work as expected (I get the mobile app served). So the functionality is working, but I can't seem to trigger it during a test run withCypress.config('userAgent')
.The text was updated successfully, but these errors were encountered: