search

Home  >  Q&A  >  body text

cy.spy that monitors the window.clearInterval function

<p>In an application I'm developing, I use setInterval and clearInterval. I want to monitor the clearInterval method to see if it is called. Here's what I'm actually doing: </p> <pre class="brush:php;toolbar:false;">beforeEach(() => { cy.clock(new Date()) }) it('Test scenario' => { const fn = cy.spy(document.defaultView, 'clearInterval') //Also tried fn = cy.spy(window, 'clearInterval') ... ... ... //The clearInterval function is called when entering the `then` section, but the stub reports that it has not been called yet cy.tick(30000).then(() => { expect(fn).to.have.been.calledOnce }) }) afterEach(() => { cy.clock().invoke('restore') })</pre> <p>The expect assertion in the snippet above fails, I expect it to pass. Is my logic for initializing the spy valid|correct? Any help with the above issue is greatly appreciated. </p>
P粉023326773P粉023326773542 days ago505

reply all(1)I'll reply

  • P粉745412116

    P粉7454121162023-08-18 10:40:22

    Cypress uses different window in tests and applications. cy.spy(window... is using the test window, but to monitor the application window, you need to use the cy.window() command.

    let spy;
    cy.window().then(appWindow => {
      spy = cy.spy(appWindow, 'clearInterval')
    })
    
    ... later
    
    expect(spy).to.have.been.calledOnce
    

    But there may be another complication, because cy.clock() puts clearInterval() in the proxy so that the application's timing function can be controlled, so You may not be able to monitor it.

    If you find that it still doesn't work properly, please get the return value of cy.clock() and see if the call information is attached.

    let clock;
    beforeEach(() => {
      clock = cy.clock(new Date())
    })
    

    Or specify clearIntervalshould not be proxied

    beforeEach(() => {
      cy.clock(new Date(), ['Date', 'setInterval'])  // 仅代理Date和setInterval
    })
    

    reply
    0
  • Cancelreply