Access JavaScript variables served by the website in test with cypress

Viewed 837

I wondered if it was possible to get access to a variable which is served in JS by the page which I'm testing.

Website serves Javascript:

var varyingUrl  = 'www.google.com';

A cypress test

Cypress.Commands.add('closeAccount', () => {
    var url = varyingUrl;
    cy.request(url)
})

I'm almost certain this isn't possible but I thought I'd ask in case someone has found a way to gain access to these available javascript variables available to the dom using cypress

1 Answers

This answer was initially found for a similar Vue/Cypress question answered by @Richard Matsen - His answer can be found here

Essentially, we just call the window with cypress then using the window, we'll access our variables.

Using the example above, you can get variables which are server is loaded via js source files:

Solution

Your variable to get

var varyingUrl  = 'www.google.com';

The cypress code:

cy.window().then((win) => {
    // use this area to code using the variable, prepending with "win." eg.
    cy.log(win.varyingUrl) // or console.log(win.varyingUrl)

})

Console output:

'www.google.com'
Related