Search code examples
jqueryautomationcypressviewportuser-agent

Useragent automation is not working in cypress to test in mobile view. Tried viewport as well but failed


I am currently trying to automate a website for its mobile view using cypress. I tried using viewpoint but it seems that the site isn't responsive enough. https://i.sstatic.net/TrHKA.png I used userAgent as well but it is not working. Here are some of the codes that I tried:

///<reference types = "Cypress"/>


describe("Test for mobile view", () => {
//method 1: using viewport
    beforeEach(() => {
       cy.viewport('iphone-x')
    })

// method 2: using useragent
    before(() => {
        cy.visit('https://www.bookmundi.com/', {
            onBeforeLoad: win => {
                Object.defineProperty(win.navigator, 'userAgent', {
                    value: 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
                });
            },
        });
    });
//method 3: using both useragent and viewport
    beforeEach(() => {
       Cypress.config('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/15A372 Safari/604.1");
       cy.viewport('iphone-6')  // Set viewport to 375px x 667px
    });


    it("should be able to go to home page", () => {
//method 4: tried by keeping random size
        Cypress.config({
           viewportHeight: '375px',
           viewportWidth: '667px',
           userAgent: 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Mobile Safari/537.36'
        })
        cy.visit("https://www.bookmundi.com/"); //homepage

//method 5:tried using headers
        cy.visit('https://www.bookmundi.com/', {
          headers: { 'user-agent': 'mobile' }
        });
    });
});

Solution

  • Please try setting userAgent in cypress.json config file.

    {
      "baseUrl": "https://www.bookmundi.com",
      "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/15A372 Safari/604.1"
    }  
    

    Test

    it('my test', () => {
      cy.viewport('iphone-x')
      cy.visit('/')
    })
    

    brian-mann commented on 23 Aug 2018

    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 cypress run --config userAgent=...