1

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?

Fody
  • 23,754
  • 3
  • 20
  • 37
asotos
  • 327
  • 3
  • 14

1 Answers1

1

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.

Fody
  • 23,754
  • 3
  • 20
  • 37
  • I'm not visiting a specific page to test. I'm doing a component test @Fody – asotos Sep 29 '21 at 22:27
  • Ok, vital piece of info. I don't think `window:before:load` will fire during a component test. – Fody Sep 30 '21 at 02:35
  • I've done what you said in beforeEach callback, But when I console.log Cypress.vue.aurora on a test case, it returns an empty object due to aurora data's fallback. So when the mixin is executed, window.Aurorara is still undefined – asotos Sep 30 '21 at 14:57
  • I can't tell from your comment what's going wrong, but can tell you the above works. Perhaps it's something to do the beforeEach. – Fody Sep 30 '21 at 19:54
  • I've managed to work with your solution. I'm pretty new to cypress and I was running `cypress open` to run the component tests. Thanks for your help! – asotos Oct 01 '21 at 13:09