测试使用全局事件总线的 Vue 单文件组件

Testing Vue Single File Components which use a Global Event Bus

我第一次使用 Mocha 和 Webpack 测试我的 Vue 组件,并根据 docs.

设置所有内容

但是,在我的许多组件中,我使用 global event bus 在组件之间进行通信和发出事件。例如,以下代码片段位于我的单个文件组件之一的创建挂钩中。

created() {
            Event.$on("activate-edit-modal", (listing) => {
                this.isModalActive = true; // show delete modal
                this.listing = listing; // set listing as the emitted listing
            });
        },

不幸的是,当我 运行 我的测试文件 (npm 运行 test) 中的以下测试代码时,出现以下错误。

import { mount } from '@vue/test-utils';
import editModal from '../../../src/components/admin/editModal.vue';

const wrapper = mount(editModal);
console.log(wrapper);

错误消息: 我知道错误消息指的是创建的挂钩(在上面的代码片段中)并在创建的挂钩中突出显示 "Event.$on"不是函数。

WEBPACK Compiled successfully in 2331ms

MOCHA Testing...

[Vue warn]: Error in config.errorHandler: "TypeError: Event.$on is not a function" TypeError: Event.$on is not a function at VueComponent.created ...

我应该如何测试使用全局事件总线的组件?请注意,我对测试事件总线本身不感兴趣;但是,我不知道如何继续测试出现此错误的组件的其他方面。

我在所有组件中使用的全局事件总线 "Event" 在 /src/main.js 中声明,如下所示

import Vue from 'vue';
import App from './App.vue';
import router from "./router";
import store from "./store";

window.Event = new Vue();

let app = new Vue({
    el: '#app',
    router,
    store,
    render: h => h(App)
});

你的全局事件总线"Event":它是在哪里定义的?我看不到它被错误地导入到组件中的任何地方。我怀疑这是你的问题。

根据最近的 vue conf 上的一个演示文稿,请注意全局事件总线是排名前五的反模式。我更喜欢普通的全局 javascript 对象作为全局状态存储。

您可以模拟您的事件总线并断言使用正确的参数调用它的方法。

例如,在上面的场景中尝试 window.Event = { $on: sinon.spy() }。

安装后您应该能够断言 $on 是使用正确的参数调用的。

这是关于 Mocha 和间谍的文档。 https://github.com/mochajs/mocha/wiki/Spies

我对 mocha 不太熟悉,所以我不确定我的细节是否正确。

您正在尝试引用名为 Event 的本地事件总线。您应该调用在 window 对象上注册的总线,如下所示:window.Event.$on("activate-edit-modal"....

在确保您的组件正在调用在 window 对象上注册的总线(如上所示)之后,请确保在将组件安装到测试文件之前添加以下内容,如下所示:

import Vue from 'vue';

window.Event = new Vue();
const wrapper = mount(adminResults);