in vue.js project have following vuex action:
import { http } '@/services/http' export const actions = { loginuser ({ commit }, params) { http.post( 'v1/login', { email: params.email, password: params.password } ).then(response => { localstorage.setitem('access_token', response.data.token) commit('set_user', response.data) }).catch(error => { commit('set_login_error', error.response.data.error) }) } }
i'm using mocha + karma unit tests. how can test action?
it's important mock/stub dependencies. first challenge mocking http
service because, written, tests won't pass unless have internet connection backend server. dependency injection solve this.
to test actions, borrowed idea vuex's suggestion. create stub of commit
function accepts type , payload of each mutation action calls , compare expected. if list of expected mutations match list of mutations commit
stub calls when action executed, action passes test.
this trivial example wouldn't use in production, helps illustrate idea:
let count = 0 let errors = [] let mutations = [ { type: 'set_user', payload: 'whatever response.data expected be' } ] function commit(type, payload) { const mutation = mutations[count] try { expect(mutation.type).to.equal(type) if (payload) { expect(mutation.payload).to.deep.equal(payload) } } catch (error) { errors.push(error) } count++ } actions.loginuser({ commit }, { email: 'fake@email.com', password: '12345' })
Comments
Post a Comment