简体   繁体   中英

How to expose vuex store of nuxt app to cypress?

I want to create tests for a vuex store with cypress for a project built with nuxt. The problem is that I cannot find a way to expose the store to cypress so that I can dispatch actions from within a test like so (code taken from this answer ):

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

The answer closest to my problem can be found here . But this seems to be a valid answer only for a vue.js app built without nuxt, especially since the Nuxt documentation indicates that nuxt has deprecated what it calls the classic mode for instatiating stores, which is the method used in the refered answer.

Any help would be greatly appreciated.

You should expose it in nuxt via client-side plugin:

// plugins/cypress.js

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

export default ({ store }) => {
  if (isCypress) {
    window.store = store
  }
}

Then in cypress you can test it:

// cypress/integration/example.spec.js

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

The store is also accessible through the NuxtJS helper, $nuxt . You access it in Cypress through the window :

cy.window()
  .its('$nuxt')
  .then((nuxt) => {
    console.dir(nuxt.$store)
  })

You could do it in plugin. Eg create a client only plugin that will set store to window

plugins/exposestore.client.js

export default ({store}) => {
  window.__store__ = store
}

I struggled with this for a few days because I was experiencing some sort of race condition between Cypress and my app. Instead of a plugin, I added the browser check into the mounted function of my layout/default.ts file:

mounted() {
        if (window.frameElement !== null && window.frameElement.id.includes('Your App')) {
            window.store = this.$store;
        }
    },

Also keep in mind when verifying that there are two windows in this case: your Cypress window and your app window within Cypress.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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