Home > Mobile >  Cypress - userAgent switch
Cypress - userAgent switch

Time:03-15

I am unable to change/override userAgent using config file. my cypress json:

env object: {
    "platform" : "mobile"
}

my plugins/index.js

module.exports = (on, options, config) => {
.
.
several on()s
.
.

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
  }) 
}

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. config is passed into module.export, so I'm clueless. What did I miss?

note: Viewport is not an option, I need to use userAgent and cy.visit() header info modification is deprecated.

Thanks!

CodePudding user response:

The principle looks ok, you should be able to change user agent in plugins.

The syntax is wrong though, on() is catching an event and it needs an event name parameter: on('<event>', config => {.

But you don't really have or need an event for this, just modify the config inline

module.exports = (on, options, 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'
  } 

  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
}
  • Related