我只想测试myAwesome
组件为App.vue
时是否调度created()
操作。这是你要测试的东西吗?我使用Jasmine进行这些测试。任何帮助都会很棒!
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
nextTickHandler@webpack:///~/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
nextTickHandler@webpack:///~/vue/dist/vue.esm.js:454:0 <- index.js:3934:16
答案 0 :(得分:0)
问题是,您正在尝试从组件中对存储进行单元测试,因此当您模拟某些元素并依赖于其他元素中的真实功能时,会出现一些问题。我不是vuex的专家,我有一个类似的问题试图窥探商店行为并调用组件的方法(不记得问题是什么,我记得我浪费了半天的时间)。
我的建议:将测试组件作为单元,然后将测试存储模块作为单元,这意味着在您的应用程序组件中可以窥探
spyOn(vm, 'myAwesomeAction');
Vue.nextTick(() => {
expect(vm.myAwesomeAction).toHaveBeenCalled()
done()
});
(也就是说,检查是否初始化组件,调用调用store操作的方法,在我的示例中myawesomeaction将是methods对象中的mapAction名称)
然后,您可以对您的商店进行单元测试,并检查如果您调用myawesomeaction,则会发生该组件的突变
在此处检查测试操作助手:https://vuex.vuejs.org/en/testing.html