感谢您的浏览。
我正在尝试在 Vuex 支持的应用程序上运行自动化测试,但无法诊断为什么在 Mocha 测试文件中提交突变会导致 Vuex 发出警告,指出我正在直接修改状态,即使它已修改突变内。我使用 Vuex 来跟踪全局状态并根据全局状态渲染某些元素(例如,如果 state.status === 'INITIAL'
则显示 buttonA,如果 state.status 显示 buttonB ===“正在加载”
)。
例如,我有一个中央存储:state = { status: 'INITIAL' };
然后我有一个相应的突变:
'LOADING': (state) => {
state.status = 'LOADING';
},
然后,如果我通过组件或存储操作正常提交更改,它就可以正常工作:this.$store.commit('INITIAL');
但是,如果我尝试建立相同的 Vuex 存储并在 Mocha 测试文件中提交相同的更改,则会出现错误:
'[Vue warn]: Error in callback for watcher "function () { return this._data.$$state; }": "Error: [vuex] Do not mutate vuex store state outside mutation handlers."
突变正确发生并且测试顺利通过,但在突变设置时它给了我这个警告:state.status = 'LOADING';
我尝试将发送提交请求移至操作内,但这并没有解决问题。我尝试更改 store/Vue 的声明位置,但这并没有解决问题。我尝试为商店设置 strict: false
,但这并没有解决问题,甚至没有隐藏它。
我不觉得我在做一些不正常的事情来测试提交,但我可能完全偏离了基础。如果我需要提供更多信息、错误转储或示例存储库,请告诉我。
谢谢! 基思
最佳答案
我发现在代码的其他地方,我正在创建一个全局 Vuex 商店。后来我在测试代码中实例化了另一个商店。测试代码有效,但 Vuex 存储的“官方”实例注意到对象正在其控制范围之外发生变化(因为第二个 Vuex 存储正在修改它)。
为了了解更多上下文,我有一个模块,counter.js
:
const store = {
count: 0
}
const mutations = {
increment(state) {
state.count++;
}
}
export default {
store,
mutations
}
在我的 store.js
文件中,我有
import counter from './store/modules/counter'
...
const store = new Vuex({
modules: {
counter
}
})
在我的 test.spec.js
文件中,我有
import counter from './store/modules/counter'
...
describe('something', () => {
it('does something', () => {
let store = new Vuex({
modules: {
counter
}
})
store.commit('increment')
})
})
当 Vuex 创建 store 时,它不会复制 store
和 mutations
对象,它只是保存传递给它的引用,设置适当的检查和其他 Hook 。运行测试时,这种情况会发生两次(或更多次),并导致抛出错误 - 尽管是在不同的范围内,因此 Mocha 不会将其标记为失败的测试。
关于vue.js - Vuex + 摩卡 : Committing mutations in tests throws warning 'Do not mutate vuex store state' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47913607/