如何使用赛普拉斯与打印版面进行交互

时间:2019-10-24 00:44:00

标签: cypress

我有一个打印按钮,单击该按钮可显示打印布局。如何使用赛普拉斯与“印刷”版面进行交互。我想在这里检查几件事:

cypress version: 3.5.0 (latest)

1) Check the text "Print" available in `h1` inside the header container div, see image

enter image description here

2) Click on the `Cancel` button: please see the html image below 

enter image description here

以下是我的柏树测试,但这无法识别CypressError: Timed out retrying: Expected to find element: 'print-preview-app', but never found it.

context('Print button tests', () => {
            it.only('Print action displays correct data', () => {
                cy.get('.timetable-filter-panel-button.btn.btn-primary > span')
                    .contains("Print current view")
                    .click();
                cy.get('print-preview-app').find('#sidebar').find('#header').find('#headerContainer').find('h1').contains("Print")

            })
        })

1 个答案:

答案 0 :(得分:0)

这是我的代码,用于测试调用window.print()方法的按钮,该方法将打开打印对话框。

我使用stub是因为它阻止了实际的打印方法并记录了发生的情况。另一个选项是spy,它记录了方法调用但“传递”,因此实际调用将发生。

Cypress.Commands.add('wasCalled', (stubOrSpy) => {
  expect(stubOrSpy).to.be.called;
})

it(`should call Print dialog`, () => {

  /* NOTE: Cannot stub outside of it() */
  let printStub

  cy.window().then(win => {
    printStub = cy.stub(win, 'print')
    cy.contains(selectorForPrintButton, 'Print').click();
    cy.wasCalled(printStub)
  })
})

我刚刚添加了一条小命令cy.wasCalled(),因为从文档this section看来,测试存根的唯一方法是使用expect(...)表达式。

在某些情况下,在测试中顺序使用expect可能是一个问题,因为据我所知,expect是同步的,因此可能会在先于{{ 1}}命令完成(例如,调用动画的cy)。

通过将其放入自定义命令中,click()被有效地添加到命令链中。我可能在这里误解了一些东西,但是除了模式expect以外,找不到任何赛普拉斯的官方示例。


如果要实际打开“打印”对话框,然后将其关闭,则可以通过在文档上键入{esc},也许是expect(stub).to.be.called来做到这一点。我没有尝试过。-不起作用。

如果我们假设打印对话框是另一个窗口,那么这个答案Access a new window - cypress.io表示您无法与之交互。

它确实显示了如何正确测试存根被调用的方法(请参阅上面的注释)

cy.document().type({esc})