Testing

Try this lesson on Scrimba

The main parts we want to unit test in Vuex are mutations and actions.

Testing Mutations

Mutations are very straightforward to test, because they are just functions that completely rely on their arguments. One trick is that if you are using ES2015 modules and put your mutations inside your store.js file, in addition to the default export, you should also export the mutations as a named export:

  1. const state = { ... }
  2. // export `mutations` as a named export
  3. export const mutations = { ... }
  4. export default createStore({
  5. state,
  6. mutations
  7. })

Example testing a mutation using Mocha + Chai (you can use any framework/assertion libraries you like):

  1. // mutations.js
  2. export const mutations = {
  3. increment: state => state.count++
  4. }
  1. // mutations.spec.js
  2. import { expect } from 'chai'
  3. import { mutations } from './store'
  4. // destructure assign `mutations`
  5. const { increment } = mutations
  6. describe('mutations', () => {
  7. it('INCREMENT', () => {
  8. // mock state
  9. const state = { count: 0 }
  10. // apply mutation
  11. increment(state)
  12. // assert result
  13. expect(state.count).to.equal(1)
  14. })
  15. })

Testing Actions

Actions can be a bit more tricky because they may call out to external APIs. When testing actions, we usually need to do some level of mocking - for example, we can abstract the API calls into a service and mock that service inside our tests. In order to easily mock dependencies, we can use webpack and inject-loader to bundle our test files.

Example testing an async action:

  1. // actions.js
  2. import shop from '../api/shop'
  3. export const getAllProducts = ({ commit }) => {
  4. commit('REQUEST_PRODUCTS')
  5. shop.getProducts(products => {
  6. commit('RECEIVE_PRODUCTS', products)
  7. })
  8. }
  1. // actions.spec.js
  2. // use require syntax for inline loaders.
  3. // with inject-loader, this returns a module factory
  4. // that allows us to inject mocked dependencies.
  5. import { expect } from 'chai'
  6. const actionsInjector = require('inject-loader!./actions')
  7. // create the module with our mocks
  8. const actions = actionsInjector({
  9. '../api/shop': {
  10. getProducts (cb) {
  11. setTimeout(() => {
  12. cb([ /* mocked response */ ])
  13. }, 100)
  14. }
  15. }
  16. })
  17. // helper for testing action with expected mutations
  18. const testAction = (action, payload, state, expectedMutations, done) => {
  19. let count = 0
  20. // mock commit
  21. const commit = (type, payload) => {
  22. const mutation = expectedMutations[count]
  23. try {
  24. expect(type).to.equal(mutation.type)
  25. expect(payload).to.deep.equal(mutation.payload)
  26. } catch (error) {
  27. done(error)
  28. }
  29. count++
  30. if (count >= expectedMutations.length) {
  31. done()
  32. }
  33. }
  34. // call the action with mocked store and arguments
  35. action({ commit, state }, payload)
  36. // check if no mutations should have been dispatched
  37. if (expectedMutations.length === 0) {
  38. expect(count).to.equal(0)
  39. done()
  40. }
  41. }
  42. describe('actions', () => {
  43. it('getAllProducts', done => {
  44. testAction(actions.getAllProducts, null, {}, [
  45. { type: 'REQUEST_PRODUCTS' },
  46. { type: 'RECEIVE_PRODUCTS', payload: { /* mocked response */ } }
  47. ], done)
  48. })
  49. })

If you have spies available in your testing environment (for example via Sinon.JS), you can use them instead of the testAction helper:

  1. describe('actions', () => {
  2. it('getAllProducts', () => {
  3. const commit = sinon.spy()
  4. const state = {}
  5. actions.getAllProducts({ commit, state })
  6. expect(commit.args).to.deep.equal([
  7. ['REQUEST_PRODUCTS'],
  8. ['RECEIVE_PRODUCTS', { /* mocked response */ }]
  9. ])
  10. })
  11. })

Testing Getters

If your getters have complicated computation, it is worth testing them. Getters are also very straightforward to test for the same reason as mutations.

Example testing a getter:

  1. // getters.js
  2. export const getters = {
  3. filteredProducts (state, { filterCategory }) {
  4. return state.products.filter(product => {
  5. return product.category === filterCategory
  6. })
  7. }
  8. }
  1. // getters.spec.js
  2. import { expect } from 'chai'
  3. import { getters } from './getters'
  4. describe('getters', () => {
  5. it('filteredProducts', () => {
  6. // mock state
  7. const state = {
  8. products: [
  9. { id: 1, title: 'Apple', category: 'fruit' },
  10. { id: 2, title: 'Orange', category: 'fruit' },
  11. { id: 3, title: 'Carrot', category: 'vegetable' }
  12. ]
  13. }
  14. // mock getter
  15. const filterCategory = 'fruit'
  16. // get the result from the getter
  17. const result = getters.filteredProducts(state, { filterCategory })
  18. // assert the result
  19. expect(result).to.deep.equal([
  20. { id: 1, title: 'Apple', category: 'fruit' },
  21. { id: 2, title: 'Orange', category: 'fruit' }
  22. ])
  23. })
  24. })

Running Tests

If your mutations and actions are written properly, the tests should have no direct dependency on Browser APIs after proper mocking. Thus you can simply bundle the tests with webpack and run it directly in Node. Alternatively, you can use mocha-loader or Karma + karma-webpack to run the tests in real browsers.

Running in Node

Create the following webpack config (together with proper .babelrc):

  1. // webpack.config.js
  2. module.exports = {
  3. entry: './test.js',
  4. output: {
  5. path: __dirname,
  6. filename: 'test-bundle.js'
  7. },
  8. module: {
  9. loaders: [
  10. {
  11. test: /\.js$/,
  12. loader: 'babel-loader',
  13. exclude: /node_modules/
  14. }
  15. ]
  16. }
  17. }

Then:

  1. webpack
  2. mocha test-bundle.js

Running in Browser

  1. Install mocha-loader.
  2. Change the entry from the webpack config above to 'mocha-loader!babel-loader!./test.js'.
  3. Start webpack-dev-server using the config.
  4. Go to localhost:8080/webpack-dev-server/test-bundle.

Running in Browser with Karma + karma-webpack

Consult the setup in vue-loader documentation.