Complete Vue.js 2 Web Development_ Practical guide to building end-to-end web development solutions with Vue.js 2

(singke) #1
Large Application Patterns with Vuex Chapter 18

If you are using the official Webpack template, you can run your tests
with npm run unit. This uses PhantomJS by default, which doesn't
implement some features. You can either use Babel polyfills or simply go
into karma.conf.js and write Chrome instead of PhantomJS in the
browsers array. Remember to install the Chrome launcher with npm
install karma-chrome-launcher --save-dev.

Testing actions

Testing actions means testing that the action commits the expected mutations. We are not


interested in the mutations themselves (not in unit tests at least) because they are already
tested separately. We might, though, need to mock some dependencies.


To avoid any dependencies from Vue or Vuex (since we don't need them and they may


pollute the tests), we create a new actions.js file inside the store directory. Install Axios


with npm install axios. The actions.js file can look like the following:


import axios from 'axios'

export const actions = {
downloadNew ({ commit }) {
axios.get('/myNewPosts')
.then(({ data }) => {
commit('ADD_ITEMS', data)
})
}
}

To test for requirement number 2, we start by mocking the call to the server that should


download the new to-do items:


describe('actions', () => {
const actionsInjector =
require('inject-loader!@/store/actions')
const buyHouseTodo = {
id: 84,
text: 'Buy house',
done: true
}
const actions = actionsInjector({
'axios': {
get () {
return new Promise(resolve => {
resolve({
data: [buyHouseTodo]
Free download pdf