Home > other >  Is there a way to access global vars from the target website via cypress?
Is there a way to access global vars from the target website via cypress?

Time:10-26

I've got a website that I want to test with cypress. This website is working with coordinates, which are stored in a global var.

I want to write a test that accesses these coordinates and checks if they are right. Is there any way to do this with cypress?

I mean, there is a way to access the vars in the DevTools (Chrome) via the Console, so it should also be possible with cypress, right...?

Thanks for helping! <3

I searched on the web but did not find anything about this. I tried (like in the chrome DevTools) to access the vars directly but it did not work...

Edit: WAIT! im dumb...

I did not realised that my "global" var is the same as the "window" var.... So, i now accessing it with the solution from @Nichola Walker

CodePudding user response:

If by global var you mean const coordinates = or let coordinates = or var coordinates = , then you can expose a reference to the variable on window, which is a global context that is common to both the app and the test.

In the app

const coordinates = {x:1, y:2}
if (window.Cypress) {            // if window.Cypress is defined then we are testing 
  window.coordinates = coordinates
}

In the test

cy.window().then(window => {
  expect(window.coordinates).to.deep.eq({x:1, y:2})    // passes
})

CodePudding user response:

If I understood you correctly, the answer is no, You cannot access the global variables of the website.

You could expose any value through the window object or through the different storages like cookies, sessions, and local storage.

Then you can access them easily through cypress.

  • Related