Is there a programmatic way to change user agent in Cypress.io?

妖精的绣舞 提交于 2020-01-13 09:31:06

问题


I have some ad calls that are only made on mobile devices. In Chrome, I can use Device Mode and simulate a mobile device, and the resulting ad call from the server is correctly tailored to mobile. I'm not sure how Chrome does this, except possibly by sending a different user agent.

In the Cypress.io documentation, it says the user agent can be changed in the configuration file (Cypress.json). But, I need to run a test for a desktop viewport and then a mobile viewport with a mobile user agent. Is there a way to change the user agent programmatically?


回答1:


The other answers do not set the User-Agent header of the underlying HTTP request, just the userAgent property of win.navigator. To set the User-Agent header to a custom value for all HTTP requests, you can set the userAgent configuration option:

{
  // rest of your cypress.json...
  "userAgent": "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"
}

You've mentioned that you don't want to use cypress.json. The user agent can be set programmatically, per spec-file, by using Cypress.config():

Cypress.config('userAgent', 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)')



回答2:


Little late to the party, but if you need, for example, set userAgent as Googlebot:

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)',
            });
        },
    });
});



回答3:


Since Cypress tests are written in Javascript you can set the user agent using the Object.defineProperty() method, for example:

Object.defineProperty(navigator, 'userAgent', {
    get: function () { return 'Mozilla/5.0 (Windows NT 6.2; WOW64; 
    rv:28.0) Gecko/20100101 Firefox/28.0)'; }
});

Then, to change the viewport you can use the cy.viewport() command. In the Cypress documentation here you can find examples on how to organize your desktop vs mobile tests separately and how to dynamically test multiple viewports.



来源:https://stackoverflow.com/questions/51048880/is-there-a-programmatic-way-to-change-user-agent-in-cypress-io

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!