Cypress-需要来自不同URL的多个页面中的数据

问题描述 投票:0回答:1

我是柏树新手。我的情况如下:

1)转到测试页。

2)启动一个初始化脚本,该脚本与服务器交互并创建一些会话。

3)进入后台

4)看到新的会话出现在表中

sessionId是从测试页接收的。启动会话时,我会获得sessionId作为响应(它是测试的一部分)。

问题是,当我去后台(通过使用cy.visit)时,整个赛普拉斯会话都会重置,并且我丢失了sessionId。

我尝试使用全局变量和别名,但无济于事。

是否可以将sessionId变量传递给后台测试?

这是我的代码:

describe('Session init', () => {
let requestBody;
let responseBody;
let sessionId;
  describe('Init the session in the client', () => {
    before(() => {
      cy.server();
      cy.route({
        method: 'POST',
        url: initUrl,
        onRequest: (xhr) => {
          requestBody = xhr.request.body;
        },
        onResponse: (xhr) => {
          responseBody = xhr.response.body;
        }
      }).as('init');
      visitTestPage(); // uses cy.visit to go to the test page - also initiates a new session
    });

    it('should send POST init request', () => {
      cy.wait('@init').then(() => {
        expect(requestBody).to.contain.keys(
          keysToExpectInRequest
        );
      });
    });

    it('should receive an init response', () => {
      cy.wrap(responseBody.session).as('session');
      sessionId = responseBody.session;
      expect(responseBody).to.contain.keys(
        keysToExpectInResponse
      );
    });
  });

  describe('Verify a session was created in backoffice', () => {
    before(() => {
      backofficeLogin(); // using cy.server and cy.visit, using premade jwt to avoid UI login
    });

    it('should see a live session with the id from the init', () => {
      cy.get('.session-row').then((sessions) => {
        expect(session[0].id).toEqual(sessionId); // expect the latest session created to be with the id of the session created in the test page
      });
    });
  });
});
e2e-testing cypress
1个回答
0
投票

如果将sessionId保存在cookie中,则可以使用此方法:

cy.wrap(responseBody.session).as('session');
sessionId = responseBody.session;
cy.setCookie('sessionId', sessionId);

doc

但是不建议这样做,因为您执行的每个测试都必须彼此独立:doc

© www.soinside.com 2019 - 2024. All rights reserved.