监视window.clearInterval函数的cy.spy
<p>在我正在开发的应用程序中,我使用 setInterval 和 clearInterval。我想要监视 clearInterval 方法,以便查看是否调用了该方法。以下是我实际在做的事情:</p>
<pre class="brush:php;toolbar:false;">beforeEach(() => {
cy.clock(new Date())
})
it('测试场景' => {
const fn = cy.spy(document.defaultView, 'clearInterval')
//也尝试过 fn = cy.spy(window, 'clearInterval')
...
...
...
//进入`then`部分时会调用 clearInterval 函数,但存根报告它尚未被调用
cy.tick(30000).then(() => {
expect(fn).to.have.been.calledOnce
})
})
afterEach(() => {
cy.clock().invoke('restore')
})</pre>
<p>上面代码段中的 expect 断言失败,我期望它通过。我初始化 spy 的逻辑是否有效|正确?非常感谢对上述问题的任何帮助。</p>
Cypress在测试和应用程序中使用不同的
window。cy.spy(window...使用的是测试窗口,但要对应用程序窗口进行监视,您需要使用cy.window()命令。let spy; cy.window().then(appWindow => { spy = cy.spy(appWindow, 'clearInterval') }) ... later expect(spy).to.have.been.calledOnce但可能还会有另一个复杂性,因为
cy.clock()将clearInterval()放在代理中,以便可以控制应用程序的定时函数,所以您可能无法对其进行监视。如果发现仍然无法正常工作,请获取
cy.clock()的返回值,并查看是否附有调用信息。let clock; beforeEach(() => { clock = cy.clock(new Date()) })或者指定
clearInterval不应该被代理beforeEach(() => { cy.clock(new Date(), ['Date', 'setInterval']) // 仅代理Date和setInterval })