如何在玩笑中测试安装方法内部的全局事件总线
how to test global event bus which is inside mounted method in jest
export default class Test extends Vue {
mounted() {
this.getData();
eventBus.$on("get", (id: string) => {
this.displayData(id);
});
}
getData(){
return "hello"
}
displayData(id){
}
我已经为测试组件编写了规范,如下所示。我使用了全局事件总线并尝试检查事件是否发出。
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 事件是否发出。但它只给出空对象。
问题已通过在安装前发出事件和模拟组件解决。
export default class Test extends Vue {
mounted() {
this.getData();
eventBus.$on("get", (id: string) => {
this.displayData(id);
});
}
getData(){
return "hello"
}
displayData(id){
}
我已经为测试组件编写了规范,如下所示。我使用了全局事件总线并尝试检查事件是否发出。
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 事件是否发出。但它只给出空对象。
问题已通过在安装前发出事件和模拟组件解决。