首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >测试Vuejs EventBus

测试Vuejs EventBus
EN

Stack Overflow用户
提问于 2021-09-07 10:46:10
回答 1查看 73关注 0票数 0

我已经试图弄清楚这一点已经有一段时间了,但我不能让它工作!我在互联网上找到了一些例子,但没有什么能解决它,每次我运行我的测试时都会得到:

代码语言:javascript
复制
 Expected number of calls: 1
 Received number of calls: 0

> 186 |        expect(wrapper.vm.EventBus.$on).toHaveBeenCalledTimes(1);

该组件如下所示:

代码语言:javascript
复制
import {EventBus} from 'eventbus'
export default{
    data(){ return {}},
    mounted(){
        EventBus.$on('saveTerminal', function(){
             this.someOtherFunction()        
        })
    }
}

事件总线文件如下所示

代码语言:javascript
复制
import Vue from 'vue';
export const EventBus = new Vue();

测试看起来像这样:

代码语言:javascript
复制
    const GlobalPlugins = {
         install(v) {
            v.prototype.EventBus = new Vue();
         },
     };
    //Vue.prototype.EventBus = new Vue(); <-- I tried this also, didn't do anything
    
    // Mounting component
    const $t = () => {}
    const params = { localVue, store, router,
        propsData: {
            isEdit: false
        },
        data(){
            return {
                loading: false,
                tabIndex: 1
            };
        },
        mocks:{
            $t,
            EventBus: {
                $on: jest.fn(),
                $off: jest.fn(),
                $emit: jest.fn()
            }
        },
     }
    
    const wrapper = shallowMount(MyComponent, params)
   describe('My component', () => { 
       it('Event bus', () => {
           wrapper.vm.EventBus.$emit('saveTerminal');
    
           expect(wrapper.vm.EventBus.$on).toHaveBeenCalledTimes(1);
        expect(wrapper.vm.EventBus.$on).toHaveBeenCalledWith('saveTerminal', expect.any(Function))
       });
    })
EN

回答 1

Stack Overflow用户

发布于 2021-09-08 01:25:02

您可以使用jest.mock() to mock the EventBus module。您的测试将require()模块以访问模拟,然后验证其$on是否已被调用:

代码语言:javascript
复制
import { shallowMount } from '@vue/test-utils'
import MyComponent from '@/components/MyComponent.vue'

jest.mock('@/utils/EventBus')

describe('MyComponent.vue', () => {
  it(`listens to 'saveTerminal' upon mounting`, async () => {
    const { EventBus } = require('@/utils/EventBus')
    shallowMount(MyComponent)
    expect(EventBus.$on).toHaveBeenCalledWith('saveTerminal', expect.any(Function))
  })
})

demo

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69086805

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档