【问题标题】:Testing Vuejs EventBus测试 Vuejs EventBus
【发布时间】:2021-09-07 10:46:10
【问题描述】:

我已经尝试解决这个问题一段时间了,但我无法让它工作!我在互联网上找到了一些示例,但没有解决它,每次我运行测试时都会得到:

 Expected number of calls: 1
 Received number of calls: 0

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

组件如下所示:

import {EventBus} from 'eventbus'
export default{
    data(){ return {}},
    mounted(){
        EventBus.$on('saveTerminal', function(){
             this.someOtherFunction()        
        })
    }
}

事件总线文件如下所示

import Vue from 'vue';
export const EventBus = new Vue();

测试看起来像这样:

    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))
       });
    })

【问题讨论】:

    标签: javascript vue.js jestjs


    【解决方案1】:

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

    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

    【讨论】:

    • 这看起来很有希望,我复制了你的例子,我得到了 expect(jest.fn()).toHaveBeenCalledWith(...expected) Expected: "saveTerminal", Any Number of来电:0
    • 是的,我从演示中复制了您的示例。在这个阶段,我没有指向问题的链接。我将尝试创建一个,我从来没有为一个开玩笑的项目做过。但是你认为这是因为我运行它的环境吗?
    • 不确定。我得看看你的代码。只需 fork 我的演示,然后更新 fork 以重现问题。
    • 抱歉,不确定如果我能在其中重现问题,我已经复制了一些设置文件,我收到了奇怪的错误stackblitz.com/edit/…
    • 很遗憾,如果没有复制品,我真的无法提供太多帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-13
    • 1970-01-01
    • 2017-09-26
    • 1970-01-01
    • 2020-06-10
    • 2018-05-06
    • 2019-01-04
    相关资源
    最近更新 更多