【发布时间】:2019-07-20 07:34:39
【问题描述】:
我正在测试一个 Vue 组件,当路由中存在某个参数时,它会在我的 Vuex 存储中调用某个操作。我在用jest.fn() 嘲笑这个动作。
这是组件中的相关代码:
await this.$store.dispatch('someOtherAction');
if (this.$route.params && this.$route.params.id) {
this.$store.dispatch('selection/selectElement', parseInt(this.$route.params.id, 10));
}
这是模拟的函数:
someOtherAction = jest.fn();
selectElement = jest.fn(() => console.log("selectElement has been called"));
我的测试:
it('selects element if passed in route', async () => {
const $route = {params: {id: '256'}};
const wrapper = shallowMount(AbcModel, {
mocks: {$route},
store, localVue
});
expect(someOtherAction).toHaveBeenCalled();
expect(selectElement).toHaveBeenCalled();
});
在输出中,我可以看到“selectElement 已被调用”。显然它已经被调用了。然而,expect(selectElement).toHaveBeenCalled() 失败了。
这怎么可能?它适用于我模拟的另一个功能。替换我模拟函数的顺序并不重要。消除调用另一个函数的期望也没有关系,所以它看起来不像是冲突。
【问题讨论】:
-
你能详细说明一下吗? “它适用于我模拟的另一个函数”是什么意思?
-
'someOtherAction' 也被 jest.fn() 模拟,并且被正确调用。 @brian-lives-outdoors 下面的答案似乎解释了真正的问题是什么。