小编Jon*_*lar的帖子

如何使用 cypress 存根 contentwindow.print/使用 cypress 测试 printJS

我的程序使用printJS,这是一个帮助格式化页面内容以进行打印的库。我想用cypress编写测试来测试是否调用了打印预览。目前我有一个按钮,当点击它时调用 printJS,并且由于 cypress 无法与打印预览窗口交互,我认为将调用存根到 printJS 然后编写一个断言它被调用一次是个好主意。我知道这适用于 window.print() 因为您可以使用此代码存根。

cy.visit('http://127.0.0.1/',{
    onBeforeLoad: (win) => {
        cy.stub(win, 'print')
    }
})
Run Code Online (Sandbox Code Playgroud)

然后用这个断言

cy.contains('print').click()
cy.window().then((win) => {
    expect(win.print).to.be.calledOnce
})
Run Code Online (Sandbox Code Playgroud)

我的旧按钮

<button type="button" class="btn btn-secnodary" onclick="window.print()">
    Print
</button>
Run Code Online (Sandbox Code Playgroud)

但是我使用了printJS,这意味着我的按钮现在看起来像这样

<button type="button" onclick="printJS({printable: 'id_preview_modal_body', type: 'html'})" data-dismiss="modal">
    Print
</button>
Run Code Online (Sandbox Code Playgroud)

javascript 被加载为 print.min.js,可以在这里找到。我试图存根 contentwindow ,但到目前为止似乎还行不通。在printJS的代码中,打印发生在这里

frameElement.contentWindow.print()
Run Code Online (Sandbox Code Playgroud)

从他们的 github 页面,第 63 行

我存根的方式给出了这个问题

cy.visit('http://127.0.0.1:8000/notices/new/',{
    onBeforeLoad: (win) => {
        cy.stub(win, 'printJS')
    }
})

Uncaught TypeError: Cannot stub non-existent own property printJS
Run Code Online (Sandbox Code Playgroud)

断言也给出了这个错误

cy.window().then((win) => …
Run Code Online (Sandbox Code Playgroud)

javascript end-to-end sinon printjs cypress

6
推荐指数
1
解决办法
1789
查看次数

标签 统计

cypress ×1

end-to-end ×1

javascript ×1

printjs ×1

sinon ×1