首页 > 解决方案 > 如何测试在 jest 中安装方法内部的全局事件总线

问题描述

export default class Test extends Vue {

 mounted() {
    this.getData();
    eventBus.$on("get", (id: string) => {
      this.displayData(id);
      
    });
}

getData(){

return "hello"

}

displayData(id){

}

我已经为 Test 组件编写了规范,如下所示。我使用了全局事件总线并尝试检查是否发出事件。

const EventBus = new Vue();
const GlobalPlugins = {
    install(v:any) {
        // Event bus
        v.prototype.eventBus = EventBus;
    }
};
 const localVue = createLocalVue()
  localVue.prototype.eventBus = createLocalVue();
   localVue.use(GlobalPlugins);

  describe('Test TestSuite', () => {
    let wrapper: any
    let TestObj: any;

    beforeEach(() => {
      const mocks = {
        eventBus: {
            $on: jest.fn(),
            $emit: jest.fn()
            }
        };
    wrapper = mount(Test, {
        mocks,
        localVue,
        router
       
      });
      console.log(eventBus.$emit) ---> returns null
      TestObj = wrapper.findComponent(Test).vm;
      console.log(eventBus.$emit) ---> returns null
    });

在这里,我尝试检查是否发出了 get 事件。但它只给出空对象。

标签: vue.jsjestjsglobalevent

解决方案


通过在安装前发出事件和模拟组件来解决问题。


推荐阅读