我的程序使用printJS,它是一个帮助格式化页面内容以进行打印的库。我想用 cypress 编写测试来测试是否调用了打印预览。目前我有一个在单击时调用 printJS 的按钮,并且由于 cypress 无法与打印预览窗口交互,我认为最好将调用 printJS 然后写一个断言它被调用一次。我知道这适用于 window.print() ,因为您可以使用此代码存根。
cy.visit('http://127.0.0.1/',{
onBeforeLoad: (win) => {
cy.stub(win, 'print')
}
})
然后用这个断言
cy.contains('print').click()
cy.window().then((win) => {
expect(win.print).to.be.calledOnce
})
我的旧按钮
<button type="button" class="btn btn-secnodary" onclick="window.print()">
Print
</button>
但是我使用了 printJS,这意味着我的按钮现在看起来像这样
<button type="button" onclick="printJS({printable: 'id_preview_modal_body', type: 'html'})" data-dismiss="modal">
Print
</button>
javascript 以 print.min.js 的形式加载,可在此处找到。我试图存根内容窗口,但到目前为止似乎没有用。在 printJS 的代码中,打印发生在这里
frameElement.contentWindow.print()
从他们的 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
断言也给出了这个错误
cy.window().then((win) => {
expect(win.printJS).to.be.calledOnce
})
TypeError: [Function: init] is not a spy or a call to a spy!
我认为这是从他们的文件[Function: init]
中引用的。但我不知道如何进一步调试这个问题。任何帮助,将不胜感激。谢谢!const printJS = print.init
index.js