Cypress 等待两次产生相同的 URL

时间:2020-12-21 17:09:50

标签: javascript typescript cypress

我有一个 web 应用程序,我目前正在为它编写 Cypress 测试。我最近升级到 6.0 版,其中包含新的 cy.intercept() 方法,该方法取代了 cy.route() 方法。但是,由于测试结果不一致,我在使用时遇到了问题。

在我的页面上,当特定输入模糊时,它会向我的 api 发送一个请求,其中包含从中推导出结果的值。

编写这个测试是为了在输入中写入第一个文本,模糊焦点,清除输入,然后编写另一个文本并模糊焦点。然后我应该有 2 个 API 调用,但是在我的第二次等待中,作业名称是错误的,因为 url 仍然是第一次调用的 url。

但是,如果我删除第一个 cy.wait(),我会在第二次调用中得到正确的 url。有时测试通过,但如果我再次启动测试,它们就会失败。

我错过了什么吗?

beforeEach(() => {
  cy.visit('/page');
  cy.intercept(
    'GET',
    'https://my.api/jobs'
  ).as('sendJobName');
});  

it('...', () => {
      cy.getBySelector('myInput')
        .type('Job name 1')
        .focus()
        .blur({ force: true })
        .clear();

      cy.wait('@sendJobName').then((interception) => {
        const { url } = interception.request;
        const { statusCode, body } = interception.response;

        expect(url)
          .to.be.a('string', 'url should be a string')
          .and.satisfy(
            (url: string) =>
              url.endsWith(encodeURIComponent('Job name 1')),
            'url should end with the right job'
          );
        expect(statusCode, 'first status should be 200').to.equal(200);
        expect(
          body,
          'first body should correspond to first request'
        ).to.deep.equal([...]);
      });

      // Type a second valid job name
      cy.getBySelector('myInput')
        .type('Job name 2', { force: true })
        .focus()
        .blur({ force: true });

      cy.wait('@sendJobName').then((interception) => {
        const { url } = interception.request;
        const { statusCode, body } = interception.response;

        expect(url)
          .to.be.a('string', 'url should be a string')
          .and.satisfy(
            (url: string) => url.endsWith(encodeURIComponent('Job name 2')),
            'url should end with the right job'
          ); // This assertion fails
        expect(statusCode, 'second status should be 200').to.equal(200);
        expect(
          body,
          'second body should correspond to second request'
        ).to.deep.equal([...]);
      });
    });

0 个答案:

没有答案