如何将nuxt应用程序的vuex商店暴露给cypress?

Joh*_*n D 2 vue.js vuex nuxt.js cypress

我想为使用 cypress 的 vuex 商店创建测试,用于使用 nuxt 构建的项目。问题是我找不到一种方法将商店公开给 cypress,以便我可以从这样的测试中分派动作(代码取自这个答案):

cy.visit()
cy.window().should('have.property', '__store__')
cy.window().then( win => {
  win.__store__.dispatch('myaction')
})
Run Code Online (Sandbox Code Playgroud)

最接近我的问题的答案可以在这里找到。但这似乎仅适用于没有使用 nuxt 构建的 vue.js 应用程序的有效答案,特别是因为 Nuxt 文档表明 nuxt 已弃用它所谓的用于实例化商店的经典模式,这是参考答案中使用的方法。

任何帮助将不胜感激。

小智 5

您应该通过客户端插件在 nuxt 中公开它:

// plugins/cypress.js

const isCypress = typeof window.Cypress !== 'undefined'

export default ({ store }) => {
  if (isCypress) {
    window.store = store
  }
}
Run Code Online (Sandbox Code Playgroud)

然后在 cypress 中你可以测试它:

// cypress/integration/example.spec.js

describe('Store', () => {   
  it('Application store is exposed to cypress', () => {
    cy.visit('/')
    cy.window().should('have.property', 'store')
  })
})
Run Code Online (Sandbox Code Playgroud)


小智 5

还可以通过 NuxtJS 帮助程序$nuxt访问该商店。您可以通过以下方式在 Cypress 中访问它window

cy.window()
  .its('$nuxt')
  .then((nuxt) => {
    console.dir(nuxt.$store)
  })
Run Code Online (Sandbox Code Playgroud)