6

我的程序使用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.initindex.js

4

2 回答 2

5

问题是onBeforeLoad在 printJS 启动之前调用了钩子,当 printJS 被导入时,它会调用它的init()函数并覆盖你的存根window.print

这太快了

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

在组件加载并启动 printJS 后存根

const printStub

before(function(){

  cy.visit('http://127.0.0.1:8000/notices/new/')

  // maybe wait for loading to complete

  cy.window().then(win => {
    printStub = cy.stub(win, 'printJS')
  })
})

it('stubs printJS', () => {
  cy.contains('button', 'Print').click()
  cy.window().then(win => {
    expect(printStub).to.be.calledOnce
  })
})
于 2018-12-08T23:21:01.267 回答
0

这是对我有用的解决方案。就我而言,我在页面上有一个打印按钮。我需要点击打开窗口。我敲了敲窗户。

  cy.get('.white-header > .ui-g-12 > .pull-right').then((data) => {
  cy.window().then((win) => {
  cy.stub(win, 'open').returns("Print window is opened")
  data.click()
  expect(win.open).to.be.calledOnce
})
})
于 2020-01-08T11:01:04.570 回答