【发布时间】:2018-11-24 04:07:21
【问题描述】:
我是第一次使用 Mocha 和 Webpack 测试我的 Vue 组件,并根据 docs 进行设置。
但是,在我的许多组件中,我使用global event bus 在组件之间进行通信和发出事件。例如,以下 sn-p 在我的单个文件组件之一的 created 挂钩中。
created() {
Event.$on("activate-edit-modal", (listing) => {
this.isModalActive = true; // show delete modal
this.listing = listing; // set listing as the emitted listing
});
},
不幸的是,当我在我的测试文件 (npm run test) 中运行以下测试代码时,我收到以下错误。
import { mount } from '@vue/test-utils';
import editModal from '../../../src/components/admin/editModal.vue';
const wrapper = mount(editModal);
console.log(wrapper);
错误消息: 我知道错误消息指的是创建的钩子(在上面的代码 sn-p 中)并突出显示该创建的钩子中的“Event.$on”不是一个函数。
WEBPACK 2331ms 编译成功
摩卡测试...
[Vue 警告]:config.errorHandler 中的错误:“TypeError:Event.$on 不是 一个函数” TypeError: Event.$on 不是一个函数 在 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)
});
【问题讨论】:
标签: unit-testing webpack vue.js mocha.js