简体   繁体   English

如何在 Cypress 上将 append 转换为 window

[英]How to append to window on Cypress

I'm testing a vue app which has a mixin that relies on a window method:我正在测试一个 vue 应用程序,它有一个依赖于 window 方法的 mixin:

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我正在尝试模拟此 window object 添加以下代码以支持文件

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?不幸的是,当测试运行时,'window:before:load' 永远不会运行并且不会执行 console.log 并且不会将 append 的值传递给 window。是否有另一种方法可以拦截 window 和 append 数据到 window,以便我的组件应该测试运行时使用它?

If 'window:before:load' does not run, maybe you have placed that code in the wrong part of the spec.如果“window:before:load”没有运行,可能是您将该代码放在了规范的错误部分。

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.但我怀疑当时 Vue 可能没有设置win.Aurora ,因为它需要先启动。


Component testing组件测试

When using the Cypress component tester, you need to give an { attachTo: ... } option.使用 Cypress 组件测试器时,您需要提供一个{ attachTo: ... }选项。

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.现在window:before:load事件也将触发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM