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

标签 javascript unit-testing vue.js vue-test-utils vue-events

在这个 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()但没有成功。

对于前面的示例,我使用 mocha , chaisinon .这只是为了说明。使用 jest 回答或任何其他测试框架/断言库都受到高度赞赏。

编辑于 2020 年 2 月 25 日

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

我创建了一个 git repository article 后面的示例代码来自 medium.com .对于这个例子,我使用了 jest用于单元测试。

这是代码:

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

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

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', () => {
    // this test passes
    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', () => {
    // this test does not pass
    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', () => {
    // this test does not pass
    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', () => {
    // this test passes
    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 中的第三个测试时遇到了问题。 .如何检查发出事件时是否调用了该方法?我们应该在单元测试中测试这种行为吗?

最佳答案

  • 在测试中,您正在检查 vm.$eventBus.$off监听器被正确触发,您必须强制组件销毁。
  • 在更改名称方法测试中,我添加了一些改进:
  • 我通过了localVue使用初始化 eventHub
  • 的插件
  • 我删除了 eventHub模拟,因为它们在这里不再有效
  • 我 mock 了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');
      });
    });
    

    关于javascript - 如何在 VueJS 中测试全局事件总线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60338721/

    相关文章:

    PHP - 主体中具有不可模拟类的单元测试方法 (PHPUnit)

    Javascript深层嵌套数组过滤器

    javascript - p :calendar trigger javascript method after first view is rendered

    angularjs - 在 angularjs 中进行单元测试时如何模拟 $location

    javascript - 为什么 Vue Composition API 设置函数中未定义 "this"?

    javascript - vue 关于单元测试 - javascript

    javascript - Vuejs可拖动排序列表

    javascript - 为移动设备调整页面大小时,Bootstrap 模态会向下移动页面

    javascript - 不可变 JS - 从列表创建 OrderedMap

    Python将随机数注入(inject)测试