2017-05-06 103 views
2

我只想測試myAwesome操作是否在我的App.vue組件爲created()時調度。這是你要測試的東西嗎?我正在使用Jasmine進行這些測試。任何幫助都是極好的!如何單元測試Vuex操作是否已在VueJS中調度

App.js

describe('when app is created()',() => { 
    it('should dispatch myAwesomeAction', (done) => { 

    const actions = { 
     myAwesomeAction() { 
     console.log('myAwesomeAction') 
     // commit() 
     } 
    } 

    const state = { 
     myAwesomeAction: false 
    } 

    const mutations = { 
     LOAD_SUCCESS(state) { 
     state.myAwesomeAction = true 
     } 
    } 

    const options = { 
     state, 
     mutations, 
     actions 
    } 

    const mockStore = new Vuex.Store(options) 

    spyOn(mockStore, 'dispatch') 

    const vm = new Vue({ 
     template: '<div><component></component></div>', 
     store: mockStore, 
     components: { 
     'component': App 
     } 
    }).$mount() 

    Vue.nextTick(() => { 
     expect(mockStore.dispatch).toHaveBeenCalled() 
     expect(mockStore.dispatch).toHaveBeenCalledWith('myAwesomeAction') 
     done() 
    }) 
    }) 
}) 

錯誤:

1) should dispatch myAwesomeAction 
    App 
    Expected spy dispatch to have been called. 
webpack:///src/views/App/test/App.spec.js:49:6 <- index.js:50916:50 
webpack:///~/vue/dist/vue.esm.js:505:15 <- index.js:3985:24 
[email protected]:///~/vue/dist/vue.esm.js:454:0 <- index.js:3934:16 
    Expected spy dispatch to have been called with [ 'loadOrganisation' ] but it was never called. 
webpack:///src/views/App/test/App.spec.js:50:54 <- index.js:50918:54 
webpack:///~/vue/dist/vue.esm.js:505:15 <- index.js:3985:24 
[email protected]:///~/vue/dist/vue.esm.js:454:0 <- index.js:3934:16 

回答

0

的事情是,你正試圖單元測試從組件商店,所以有當你是一個問題的一點點嘲笑一些元素並依賴其他元素的真實功能。我不是vuex的專家,我有一個類似的問題,試圖窺探商店行爲並調用組件的方法(不記得問題是什麼,我記得我浪費了半天的時間)。

我的建議:測試組件爲單位,然後測試商店模塊爲單位,這意味着在你的應用程序組件,您可以窺探

spyOn(vm, 'myAwesomeAction'); 
Vue.nextTick(() => { 
    expect(vm.myAwesomeAction).toHaveBeenCalled() 
    done() 
}); 

(即檢查是否初始化你的組件,你的方法調用店內動作被調用,在我的例子myawesomeaction將是一個地圖行動名字在方法對象)

然後,你可以單元測試你的存儲和檢查,如果您的通話將出現myawesomeaction該組件上的突變

檢查測試行動幫手在這裏:https://vuex.vuejs.org/en/testing.html

相關問題