Unit testing 使用Jest测试Vuex存储模块
我是用笑话测试vue的初学者。 我想测试下面描述的vuex模块 bible.mudule.jsUnit testing 使用Jest测试Vuex存储模块,unit-testing,testing,jestjs,vuex,vuex-modules,Unit Testing,Testing,Jestjs,Vuex,Vuex Modules,我是用笑话测试vue的初学者。 我想测试下面描述的vuex模块 bible.mudule.js export const mutations = { setTestament(state, testament) { state.testament = testament; }, setBookList(state, list) { state.bookList = list; }, setCurrentBook(state, book) {
export const mutations = {
setTestament(state, testament) {
state.testament = testament;
},
setBookList(state, list) {
state.bookList = list;
},
setCurrentBook(state, book) {
state.currentBook = book;
},
setCurrentChapterNumber(state, chapter) {
state.currentChapterNumber = chapter;
}
}
export const actions = {
retrieveBooksByTestament( { commit } , testament) {
BibleService.retrieveBooksByTestament(testament).then(bookList => {
commit('setBookList', bookList);
})
},
changeCurrentBook({ commit }, book) {
commit('setCurrentBook', book);
commit('setCurrentChapterNumber', 1);
},
setTestament({ commit }, testament) {
commit('setTestament', testament);
}
}
export const bible = {
namespaced: true,
state: {
testament: null,
bookList: null,
currentBook: null,
currentChapterNumber: null
},
mutations: mutations,
actions: actions,
}
index.js
import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from "vuex-persistedstate";
import { bible } from "./bible/bible.module";
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
bible,
},
plugins: [createPersistedState()]
});
我试着写一个测试如下
import { shallowMount, createLocalVue } from '@vue/test-utils'
import ListOfBooksScreen from '../../src/views/ListOfBooksScreen.vue'
import BibleService from '../../src/services/BibleService'
import Vuex from 'vuex'
import bible from '../../src/store/bible/bible.module'
const localVue = createLocalVue()
localVue.use(Vuex)
describe('ListOfBooksScreen.vue', () => {
let actions
let store
window.prompt = jest.fn();
beforeEach(() => {
actions = {
retrieveBooksByTestament: jest.fn().mockName('retrieveBooksByTestament'),
setTestament: jest.fn()
}
store = new Vuex.Store({
components: {
bible: {
actions,
namespaced: true
}
}
})
})
it('calls store action "retrieveBooksByTestament" when is mounted', async () => {
const wrapper = shallowMount(ListOfBooksScreen, { store, localVue});
expect(actions.retrieveBooksByTestament).toHaveBeenCalled();
})
})
但是我得到了下面的错误
console.error node_modules/vuex/dist/vuex.common.js:1132
[vuex] module namespace not found in mapState(): bible/
console.error node_modules/vuex/dist/vuex.common.js:1132
[vuex] module namespace not found in mapActions(): bible/
另外,在我的组件中,RetrieveBooksByTestation方法是在挂载的钩子上调用的,因此我考虑
expect(actions.retrieveBooksByTestament).toHaveBeenCalled()
返回true,但从未调用该操作,测试失败并显示以下消息
Expected number of calls: >= 1
Received number of calls: 0
关于第一个问题,我知道这是由于与名称空间相关的原因,但我找不到问题所在。我正在查看vuex文档,它似乎没有问题。
关于第二个问题,我真的不知道测试是否提出得很好