如何用Jest测试Vue组件created钩子中fetch方法的调用情况?
问题分析与解决方案
你的测试出现报错及断言失败的原因主要有两点:
- 手动调用
wrapper.vm.$options.created()完全多余——shallowMount组件时,Vue会自动执行created生命周期钩子,重复调用反而可能引发异常。 - 直接
spyOn(Component.methods, 'fetch')无法追踪实例调用——Vue实例化时会将methods中的方法绑定到组件实例(重新绑定this),实例上的fetch与原Component.methods.fetch并非同一引用,导致spy失效。
正确测试方案
最可靠的方式是在挂载组件时,直接用jest mock函数覆盖组件的fetch方法,具体代码如下:
test('The fetch method should be called when the component has been created.', async () => { // 创建jest mock函数替代原fetch方法 const fetchSpy = jest.fn(); const wrapper = shallowMount(CaseDetails, { global: { mocks: { $route, $store: { state: { apiConfig: new Configuration({ basePath: 'https://localhost:3000', }), }, }, }, // 覆盖组件原有的fetch方法 methods: { fetch: fetchSpy, }, }, }); // 等待异步方法执行完成(fetch是async函数) await wrapper.vm.$nextTick(); // 断言mock函数已被调用 expect(fetchSpy).toHaveBeenCalled(); });
补充说明
如果需要保留原fetch方法的逻辑同时追踪调用,可以通过修改组件原型的方式实现:
test('The fetch method should be called when the component has been created.', async () => { // spyOn组件原型上的fetch方法 const fetchSpy = jest.spyOn(CaseDetails.prototype.methods, 'fetch'); const wrapper = shallowMount(CaseDetails, { global: { mocks: { $route, $store: { state: { apiConfig: new Configuration({ basePath: 'https://localhost:3000', }), }, }, }, }, }); await wrapper.vm.$nextTick(); expect(fetchSpy).toHaveBeenCalled(); // 测试结束后清除spy fetchSpy.mockRestore(); });
内容的提问来源于stack exchange,提问作者Ricardo de Vries
相关产品推荐
相关产品推荐

