How do you test Vuejs components when using Vuex

I am writing unit tests for my vuejs components in a larger application. My application state is in vuex repository, so almost all of my components retrieve data from vuex.

I cannot find a working example for writing unit test for this. I found

Where Evan says:

When the module tests the component separately, you can insert the mocked repository directly into the component using the store option.

But I cannot find a good example of how to test these components. I have tried many ways. Below I see how people do it. stack overflow

It basically looks like

test.vue:

<template> <div>test<div> </template> <script> <script> export default { name: 'test', computed: { name(){ return this.$store.state.test; } } } </script> 

test.spec.js

 import ... const store = new Vuex.Store({ state: { test: 3 } }); describe('test.vue', () => { it('should get test from store', () => { const parent = new Vue({ template: '<div><test ref="test"></test></div>', components: { test }, store: store }).$mount(); expect(parent.$refs.test.name).toBe(3); }); } 

Note that "ref" this example does not work without it.

Is this really the right way to do this? It seems like it will be messy because it requires adding props to the template as a string.

The Evan quote seems to imply that the store can be added directly to the child component (i.e. not to the parent component, as an example).

How do you do this?

+8
unit-testing components vuex
source share
1 answer

The answer is actually very simple, but not currently documented.

  const propsData = { prop: { id: 1} }; const store = new Vuex.Store({state, getters}); const Constructor = Vue.extend(importedComponent); const component = new Constructor({ propsData, store }); 

Note that the repository is passed to the constructor. propsData is currently documented , the "store" option is missing.

Also, if you use Laravel, there are strange problems with the webpack versions that you can run.

[vuex] should call Vue.use (Vuex),

The error was caused by using laravel-elixir-webpack-official.
If you made a correction:

npm install webpack@2.1.0-beta.22 --save-dev

for this https://github.com/JeffreyWay/laravel-elixir-webpack-official/issues/17

Your tests that include Vuex seem to break with

[vuex] should call Vue.use (Vuex)

even if you have Vue.use (Vuex)

+10
source share

All Articles