Search code examples
cypresse2e-testing

How to share a variable in Cypress from one test (it) to another when the domains are different?


How to share a variable from one test (it) to another when the domains are different? I've tried in countless ways, with Alias, Closure, Environment Variable, Local Storage, even with Event Listener, but when the next test is executed, these variables are cleared from memory.

The point is that I need to obtain the ID of an open protocol in a Web application, go to the backoffice that is in another domain to validate if that protocol was really opened. Here is the last version after giving up...

/// <reference types="cypress" />

describe("Testar abertura de protocolo no fale conosco", () => {
    it("Deve acessar o FaleConosco, abrir um protocolo e depois validar no backoffice a abertura correta do mesmo", () => {
        cy.visit(`${Cypress.env('FALE_CONOSCO_URL')}`)
        cy.get("#BotaoCriarNovoChamado").click()
        
        cy.get('#InputLabelCpfCnpj').type("99999999999")
        cy.get('#InputLabelEmail').type("email@email.com")
        cy.get('#InputLabelTelefone').type("99999999999")
        cy.get('#InputLabelAssunto').type("Assunto de teste")
        cy.get('#InputLabelDescricao').type("Essa aqui e uma descrição bem detalhada, confia")
        cy.get('#BotaoEnviar').click()

        cy.get('#spanNumeroDoChamado').should('contain', 'Número do chamado')
        cy.get('#divNumeroDoChamado').then($div => {
            const numero_do_chamado = $div.text().split(' ')[3].replace(/^#/, "");
            // cy.wrap(numero_do_chamado).as("minhaVariavel");

            // Enviar o valor do alias para o segundo domínio usando postMessage
            cy.window().then((win) => {
                win.postMessage({ type: "aliasValue", value: numero_do_chamado }, "*");
            });
            // Cypress.env('numero_do_chamado', numero_do_chamado);
            // cy.log("numero_do_chamado  -  " + Cypress.env('numero_do_chamado'));
            // cy.window().then(win => {
            // win.localStorage.setItem('numero_do_chamado', numero_do_chamado);
            // });
        });


        // cy.get('#divNumeroDoChamado').invoke("text").as("minhaVariavel")
        // // ($div => {
        // //     const numero_do_chamado = $div.text().split(' ')[3].replace(/^#/, "");
        // //     cy.wrap(numero_do_chamado).as("minhaVariavel");

        // // Enviar o valor do alias para o segundo domínio usando postMessage
        // cy.window().then((win) => {
        //     win.postMessage({ type: "aliasValue", value: cy.get("@minhaVariavel") }, "*");
        // });
        // //     // Cypress.env('numero_do_chamado', numero_do_chamado);
        // //     // cy.log("numero_do_chamado  -  " + Cypress.env('numero_do_chamado'));
        // //     // cy.window().then(win => {
        // //     // win.localStorage.setItem('numero_do_chamado', numero_do_chamado);
        // //     // });
        // // });

    });

    it("Deve acessar o Conecta e validar a abertura correta protocolo", () => {
        cy.visit(`${Cypress.env('URL')}`);

        // Receber a mensagem contendo o valor do alias enviado pelo primeiro domínio
        cy.window().then((win) => {
            win.addEventListener("message", (event) => {
                const message = event.data;

                // Verificar se a mensagem contém o valor do alias
                if (message.type === "aliasValue") {
                const aliasValue = message.value;
                cy.wrap(aliasValue).as("meuAliasCompartilhado");
                }
            });
        });

        // Fazer algo com o alias compartilhado no segundo domínio
        cy.get("@meuAliasCompartilhado").then((valor) => {
            // Faça algo com o valor do alias compartilhado
            cy.log("Valor do alias compartilhado:", valor);
            cy.login();
            cy.visit(`${Cypress.env('URL')}/ticket-container/${Cypress.env('valor')}`)

        });

    });

})

Solution

  • When the test runner changes domains the whole browser object is reset, so any variables written to browser memory are lost

    • closure variables
    • aliases
    • env var (Cypress.env).

    That leaves you with fixture (disk storage) or task-related pseudo data store (see bahmutov/cypress-data-session).

    For fixture, the code would be

    it("Deve acessar o FaleConosco...", () => {
      cy.visit(`${Cypress.env('FALE_CONOSCO_URL')}`)
      ...
        const numero_do_chamado = $div.text().split(' ')[3].replace(/^#/, "")
        cy.writeFile('cypress/fixtures/numero_do_chamado.json', numero_do_chamado)
        ...
    })
    
    it("Deve acessar o Conecta...", () => {
      cy.visit(`${Cypress.env('URL')}`)
      ...
      const numero_do_chamado = cy.readFile('cypress/fixtures/numero_do_chamado.json')
      ...
    })
    

    Don't use cy.fixture() command as there is caching involved internally. Not a problem for your current scenario, but may cause unexpected errors when your test pattern changes.