代码之家  ›  专栏  ›  技术社区  ›  Florent Arlandis

Cypress:运行时更改代码会导致我的测试崩溃(请求中止)

  •  0
  • Florent Arlandis  · 技术社区  · 5 年前

    我正在用Cypress测试一个Angular应用程序。

    我正在使用Cypress仪表板运行测试,我使用以下命令打开该仪表板: $(npm bin)/cypress open

    我正在调用API进行测试: 它奏效了 .

    但是,当我更改代码时,Cypress将重新运行代码,这将导致我的第一次(也是唯一的第一次测试)失败。 调用API的请求已中止。

    使其再次工作的唯一方法是手动结束该过程,然后重新启动。

    有人知道是什么导致了这种奇怪的行为吗?

    以下是我的测试代码:

      beforeEach(() => {
            cy.visit('/');
            cy.server();
            cy.route('POST', `myUrl`).as('apiCall');
        });
    
        it('should find a doctor when user searches doctor with firstName', () => {
            cy.get('#myInput').type('foo');
            cy.get('#submitButton]').click();
            cy.wait('@apiCall').then((xhr) => {
                expect(xhr.status).to.eq(200); 
            });
        });
    
    0 回复  |  直到 5 年前
        1
  •  0
  •   Przemyslaw Jan Beigert    5 年前

    您可以这样准备XHR存根:

    describe('', () => {
      let requests = {}; // for store sent request
    
      beforeEach(() => {
        cy.server({ delay: 500 }); // cypress will answer for mocked xhr after 0.5s
        cy.route({
          url: '<URL>',
          method: 'POST',
          response: 'fixture:response',
          onRequest: ({ request }) => {
            Object.assign(requests, { someRequest: request.body }); // it has to be mutated
          },
        });
      });
    

    然后在测试中:

    it('', () => {
      cy
        .doSomeSteps()
        .assertEqual(requests, 'someRequest', { data: 42 })
    });
    

    这种解决方案有两个优点:第一个0.5秒的延迟使测试更现实,因为真正的后端不会立即响应。其次,您可以验证应用程序是否会在以下时间发送正确的有效载荷 doSomeActions() 步骤。

    assertEqual 只是为了使断言更具可读性

    Cypress.Commands.add('assertEqual', (obj, key, value) =>
      cy
        .wrap(obj)
        .its(key)
        .should('deep.equal', value)
    );