Search code examples
javascriptvue.jscypresscypress-component-test-runner

How to append to window on Cypress


I'm testing a vue app which has a mixin that relies on a window method:

export default {
  data () {
    return {
      aurora: window.Aurora || {}
    }
  },
  methods: {
    quickView () {
      const hasQuickViewElement = document.querySelector('#product-quickview')
      if (hasQuickViewElement && this.id && typeof this.aurora.quickview === 'function') {
        this.aurora.quickview(this.id)
      }
    },
    wishlist () {
      if (this.id && typeof this.aurora.showOverlay === 'function') {
        this.aurora.showOverlay('#add-shop-list', { prodId: this.id })
      }
    }
  }
}

I'm trying to mock this window object adding the following code to support file

Cypress.on('window:before:load', (win) => {
    console.log('aaaaaaaaaaaaaaaaaaaaaaaaaaaaa', win)
    win.Aurora = 'haushuhuashuas'
  })

  Cypress.on('window:load', (win) => {
    console.log('bbbbbbbbbbbbbbbbbbbbbbbbbbbb', win)
    console.log(win.Aurora)
  })

Unfortunately when the test runs, 'window:before:load' never runs and does not execute console.log and does not append the value to the window. Is there another way to intercept the window and append data to window so that my component should use it when the test runs?


Solution

  • If 'window:before:load' does not run, maybe you have placed that code in the wrong part of the spec.

    It should be before the visit, or use an option of visit

    cy.visit('...', {
      onBeforeLoad: (win) => {
        ...
      },
    })
    

    But I suspect that Vue might not have set win.Aurora at that point, since it needs to spin up first.


    Component testing

    When using the Cypress component tester, you need to give an { attachTo: ... } option.

    const win = cy.state('window')
    win.Aurora = {
      quickview: () => 'Aurora is mocked'
    }
    
    const wrapper = mount(MyComponent, {
      attachTo: win 
    })
    

    Now the window:before:load event will fire also.