代码之家  ›  专栏  ›  技术社区  ›  Svish

如何在Cypress测试中排队

  •  0
  • Svish  · 技术社区  · 6 年前

    我有以下测试 a custom Cypress command of mine :

    it('can navigate to a url', () => {
      const history = createHistory();
      cy.window().then(win => ((win as any).__chh__history__ = history));
    
      cy.spy(history, 'push');
      history.listen((location, action) => {
        expect(action).to.equal('PUSH');
        expect(location.pathname).to.equal(PATH);
        expect(location.state).to.equal('foobar');
      });
    
      cy.navigate(PATH, 'foobar');
    
      cy.wait(0).then(() => {
        expect(history.push).to.have.been.called;
      });
    });
    

    该命令运行良好,但如果我删除 cy.wait(0) ,只做 expect ,则测试失败。

    我想这是因为 cy.navigate 命令(通过添加 Cypress.Commands.add )与其他Cypress命令一样,它被排队,这意味着 期待 实际上,在任何Cypress命令启动之前就已经运行了?

    如果是这样,那当然很好,正如预期的那样,但Cypress测试中有没有一种方法可以在不使用 cy.wait(0) ?

    例如,当我检查元素时,我可以使用 cy.get(something).should($el => expect(...)) ,但在这种情况下,没有什么“应该”的。。。我当然可以 cy.get('body') 或者别的什么,但我真的不想得到 任何东西 在这种情况下。¤

    0 回复  |  直到 6 年前
        1
  •  1
  •   Richard Matsen    6 年前

    这个 docs 展示裸体的使用 expect() 在间谍被建立之后,

    cy.spy(util, 'addListeners')  
    App.start()  
    expect(util.addListeners).to.be.called
    

    但我认为这是误导,因为 期望() 立即运行,但介入的Cypress命令可能具有固有的延迟或重定时,并且不能保证在执行预期之前完成。

    另外两种测试方法是:

    确保expect仅在您的自定义命令之后运行

    cy.navigate(PATH, 'foobar').then(() => {
      expect(history.push).to.have.been.called;
    })
    

    将期望放入Cypress命令队列

    cy.navigate(PATH, 'foobar');
    cy.wrap(history).its('push').should('have.been.called')