如何在 VueJS 中测试全局事件总线

How to test a global event bus in VueJS

在此 article 中解释了如何在 VueJS 中使用全局事件总线。它描述了使用在单独文件中定义的事件总线的常用方法的替代方法:

import Vue from 'vue';

const EventBus = new Vue();
export default EventBus;

必须在需要的每个 SFC 中导入它。替代方法将全局事件总线附加到主 Vue 实例:

// main.js
import Vue from 'vue';

Vue.prototype.$eventBus = new Vue(); // I call it here $eventBus instead of $eventHub

new Vue({
  el: '#app',
  template: '<App/>',
});

// or alternatively
import Vue from 'vue';
import App from './App.vue';

Vue.prototype.$eventBus = new Vue();

new Vue({
  render: (h): h(App),
}).$mount('#app');

现在我的问题是我不知道如何在单元测试中使用以这种方式创建的全局事件总线。

已经有一个question关于使用第一个提到的方法测试全局事件总线,但没有答案被接受。

我尝试按照 answers 之一的建议使用 createLocalVue,但这没有帮助:

it('should listen to the emitted event', () => {
  const wrapper = shallowMount(TestingComponent, { localVue });
  sinon.spy(wrapper.vm, 'handleEvent');
  wrapper.vm.$eventBus.$emit('emit-event');
  expect(wrapper.vm.handleEvent.callCount).to.equal(1);
});

这表示预期为 0,实际为 1。我尝试使用 async 函数和 $nextTick() 但没有成功。

对于前面的示例,我使用了 mochachaisinon。这只是为了说明。非常感谢使用 jest 或任何其他测试框架/断言库的答案。

2020 年 2 月 25 日编辑

读了书"Testing Vue.js Applications" from the Edd Yerburgh, author of @vue/test-utils,我有了一些想法,但我仍然在努力理解如何完成作为实例添加的全局事件总线的测试属性。在书中实例属性在单元测试中被模拟。

我创建了一个 git 存储库,示例代码遵循 medium.com 中的 article .对于这个例子,我使用 jest 进行单元测试。

这是代码:

src/main.js

import Vue from 'vue';
import App from './App.vue';

<strong>// create global event bus as instance property
Vue.prototype.$eventBus = new Vue();</strong>

Vue.config.productionTip = false;

new Vue({
  render: (h) => h(App),
}).$mount('#app');

src/App.vue

<template>
  <div id="app">
    <hello-world></hello-world>
    <change-name></change-name>
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue';
import ChangeName from './components/ChangeName.vue';

export default {
  name: 'App',
  components: {
    HelloWorld,
    ChangeName,
  },
};
</script>

src/components/HelloWorld.vue

<template>
  <div>
    <h1>Hello World, I'm {{ name }}</h1>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data() {
    return {
      name: 'Foo',
    };
  },
  created() {
    this.$eventBus.$on('change-name', this.changeName);
  },
  beforeDestroy() {
    this.$eventBus.$off('change-name');
  },
  methods: {
    changeName(name) {
      this.name = name;
    },
  },
};
</script>

src/components/ChangeName.vue 更换名字

<script>
export default {
  name: 'ChangeName',
  data() {
    return {
      newName: '',
    };
  },
  methods: {
    changeName() {
      this.$eventBus.$emit('change-name', this.newName);
    },
  },
};
</script>

这是一个非常简单的应用程序,包含两个组件。组件 ChangeName.vue 有一个输入元素,用户可以通过单击一个按钮来触发一个方法。该方法使用全局事件总线发出事件 change-name。组件 HelloWorld.vue 监听事件 change-name 并更新模型 属性 name.

以下是我尝试对其进行测试的方法:

tests\unit\HelloWorld.spec.js

import { shallowMount } from '@vue/test-utils';
import HelloWorld from '@/components/HelloWorld.vue';

describe('HelloWorld.vue', () => {
  const mocks = {
    $eventBus: {
      $on: jest.fn(),
      $off: jest.fn(),
      $emit: jest.fn(),
    },
  };

  it('listens to event change-name', () => {
    <strong>// this test passes</strong>
    const wrapper = shallowMount(HelloWorld, {
      mocks,
    });
    expect(wrapper.vm.$eventBus.$on).toHaveBeenCalledTimes(1);
    expect(wrapper.vm.$eventBus.$on).toHaveBeenCalledWith('change-name', wrapper.vm.changeName);
  });

  it('removes event listener for change-name', () => {
    <strong>// this test does not pass</strong>
    const wrapper = shallowMount(HelloWorld, {
      mocks,
    });
    expect(wrapper.vm.$eventBus.$off).toHaveBeenCalledTimes(1);
    expect(wrapper.vm.$eventBus.$off).toHaveBeenCalledWith('change-name');
  });

  it('calls method changeName on event change-name', () => {
    <strong>// this test does not pass</strong>
    const wrapper = shallowMount(HelloWorld, {
      mocks,
    });
    jest.spyOn(wrapper.vm, 'changeName');
    wrapper.vm.$eventBus.$emit('change-name', 'name');
    expect(wrapper.vm.changeName).toHaveBeenCalled();
    expect(wrapper.vm.changeName).toHaveBeenCalledWith('name');
  });
});

tests\unit\ChangeName.spec.js

import { shallowMount } from '@vue/test-utils';
import ChangeName from '@/components/ChangeName.vue';

describe('ChangeName.vue', () => {
  const mocks = {
    $eventBus: {
      $on: jest.fn(),
      $off: jest.fn(),
      $emit: jest.fn(),
    },
  };

  it('emits an event change-name', () => {
    <strong>// this test passes</strong>
    const wrapper = shallowMount(ChangeName, {
      mocks,
    });
    const input = wrapper.find('input');
    input.setValue('name');
    const button = wrapper.find('button');
    button.trigger('click');
    expect(wrapper.vm.$eventBus.$emit).toHaveBeenCalledTimes(1);
    expect(wrapper.vm.$eventBus.$emit).toHaveBeenCalledWith('change-name', 'name');
  });
});

TL;DR

这个问题很长,但是大部分都是代码示例。问题是如何对创建为 Vue 实例的全局事件总线进行单元测试 属性?

特别是我在理解 tests/unit/HelloWorld.spec.js 中的第三个测试时遇到了问题。如何检查发出事件时是否调用了该方法?我们是否应该在单元测试中测试这种行为?

  1. 在检查 vm.$eventBus.$off 侦听器是否正确触发的测试中,您必须强制组件销毁。
  2. 在更改名称方法测试中,我添加了一些改进:
    • 我通过 localVue 初始化 eventHub 的插件
    • 我删除了 eventHub 模拟,因为它们在这里不再有效
    • 我在组件设置中模拟了 changeName 方法,而不是在组件创建之后

这是我对 tests\unit\HelloWorld.spec.js 的建议:

import { shallowMount, createLocalVue } from '@vue/test-utils';
import Vue from 'vue';
import HelloWorld from '@/components/HelloWorld.vue';

const GlobalPlugins = {
  install(v) {
    v.prototype.$eventBus = new Vue();
  },
};

const localVue = createLocalVue();
localVue.use(GlobalPlugins);

describe('HelloWorld.vue', () => {
  const mocks = {
    $eventBus: {
      $on: jest.fn(),
      $off: jest.fn(),
      $emit: jest.fn(),
    },
  };

  it('listens to event change-name', () => {
    const wrapper = shallowMount(HelloWorld, {
      mocks,
    });
    expect(wrapper.vm.$eventBus.$on).toHaveBeenCalledTimes(1);
    expect(wrapper.vm.$eventBus.$on).toHaveBeenCalledWith('change-name', wrapper.vm.changeName);
  });

  it('removes event listener for change-name', () => {
    const wrapper = shallowMount(HelloWorld, {
      mocks,
    });

    wrapper.destroy();
    expect(wrapper.vm.$eventBus.$off).toHaveBeenCalledTimes(1);
    expect(wrapper.vm.$eventBus.$off).toHaveBeenCalledWith('change-name');
  });

  it('calls method changeName on event change-name', () => {
    const changeNameSpy = jest.fn();
    const wrapper = shallowMount(HelloWorld, {
      localVue,
      methods: {
        changeName: changeNameSpy,
      }
    });

    wrapper.vm.$eventBus.$emit('change-name', 'name');

    expect(changeNameSpy).toHaveBeenCalled();
    expect(changeNameSpy).toHaveBeenCalledWith('name');
  });
});