Vue测试库中Mock Mixin时的路由与方法模拟问题
问题解决方案
问题1:$route 输出 undefined 的修复
你错误地将localVue、router、mocks等测试配置放在了Component对象内部,这些属于shallowMount的配置选项,需要作为第二个参数单独传递给shallowMount,Component对象只需保留基础的组件定义(如render、mixins)。
问题2:$appboy.logCustomEvent 报错的修复
- 核心原因同样是
mocks配置位置错误,导致组件mounted钩子执行时this.$appboy未被正确模拟; - 你在组件挂载后才创建spy,但
mounted钩子已经执行完毕,无法捕获到事件调用,需要提前创建spy并传入mocks。
修正后的测试代码
import { expect } from 'chai' import { shallowMount, createLocalVue } from '@vue/test-utils' import VueRouter from 'vue-router' import sinon from 'sinon' import { CampaignNotifier } from '@/mixins/campaignNotifier' let wrapper function factory (routeName, currency) { const localVue = createLocalVue() localVue.use(VueRouter) // 创建路由实例并设置当前路由参数 const router = new VueRouter({ routes: [ { path: `/${routeName}`, name: routeName } ] }) router.push({ name: routeName, query: { currency } }) // 提前创建logCustomEvent的spy const logCustomEventSpy = sinon.spy() const Component = { render () {}, mixins: [CampaignNotifier] } // 正确传递测试配置选项 return shallowMount(Component, { localVue, router, mocks: { $appboy: { logCustomEvent: logCustomEventSpy } } }) } describe('@/mixins/campaignNotifier', () => { it('Campaign Notifier is not called if route not configured correctly', () => { wrapper = factory('before-begin', 'EUR') console.log('$route ***', wrapper.vm.$route) // 现在会输出正确的路由对象 // 直接断言spy的调用状态 expect(wrapper.vm.$appboy.logCustomEvent).not.toHaveBeenCalled() }) })
额外注意事项
如果BRAZE_TAG_MAPPING是全局变量,测试时需要提前模拟该变量,否则会出现未定义错误,可在测试文件顶部添加:
global.BRAZE_TAG_MAPPING = {}
内容的提问来源于stack exchange,提问作者David Pell
相关产品推荐
相关产品推荐

