cypress-io / cypress-vue-unit-test

A little helper to unit test Vue components in the Cypress.io E2E test runner
294 stars 23 forks source link

Using Vuex within a component #374

Closed ghost closed 3 years ago

ghost commented 3 years ago

I'm trying to test a Vue component which uses Vuex. The standard way to use Vuex is to inject it globally in main.js:

new Vue({
  router,
  store, // This injects the Vuex store into all components (eg this.$store)
  vuetify,
  render: h => h(App)
}).$mount('#app')

But then when I try to test an individual component the injected this.$store does not exist. I think I need to inject it somehow but I can't get the syntax correct. I see in your example I need to include Vuex in the plugins but how do I create the this.$store in the component?

/// <reference types="cypress" />
import { mount, mountCallback } from 'cypress-vue-unit-test'
import ArrayWidget from '@/components/widgets/ArrayWidget.vue'
import store from '../../../src/store'
import Vuex from 'vuex'
describe('ArrayWidget', () => {
  it("runs with vuex", () => {
    const extensions = {
      plugins: [Vuex],
      mixin: [store]
    }
    mount(ArrayWidget, {
      extensions,
    })
  })
})
ghost commented 3 years ago

Wow I was close. Fixed it with brackets around store:

    const extensions = {
      plugins: [Vuex],
      mixin: [{ store }]
    }

Then I had trouble actually getting and setting the store values but I was able to in a .then() method off the mount:

    mount(ArrayWidget, {
      extensions,
      propsData: {
        parameters: ['TGT', 'PKT', 'ITEM', null, null, null, null, 'RAW']
      }
    }).then(() => {
      expect(Cypress.vue.$store.state.tlmViewerItems[0]).to.eql({
        target: 'TGT',
        packet: 'PKT',
        item: 'ITEM',
        type: 'RAW'
      })
      Cypress.vue.$store.commit('tlmViewerUpdateValues', [['hello'], []])
    })