Skip to content

Instantly share code, notes, and snippets.

@FernandoBasso
Created January 30, 2018 12:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FernandoBasso/e3a0cfc5b2ba6d754833d1e07d33b16c to your computer and use it in GitHub Desktop.
Save FernandoBasso/e3a0cfc5b2ba6d754833d1e07d33b16c to your computer and use it in GitHub Desktop.
vuejs test emitted events with sinon spy
import Vue from 'vue';
import Foo from '../src/components/Foo.vue';
import expect from 'expect';
import sinon from 'sinon';
import { mount } from '@vue/test-utils';
// Can comment out the mocks property and use this. Both work.
// Vue.prototype.$ebus = new Vue();
describe('Foo', () => {
let wrp;
beforeEach(() => {
wrp = mount(Foo, {
mocks: {
$ebus: new Vue(),
}
});
});
it('displays the inserted message', () => {
let input = wrp.find('input.msg');
input.element.value = 'Message #1 from Foo';
input.trigger('input');
expect(wrp.find('.display-msg').html()).toContain('Message #1 from Foo');
});
it('sends an event through ebus', () => {
let spy = sinon.spy(wrp.vm.$ebus, '$emit');
let input = wrp.find('input.msg');
input.element.value = 'Message #2 from Foo';
input.trigger('input');
console.log(spy.callCount);
expect(spy.callCount).toBe(1);
expect(spy.calledWithExactly('msg-sent', 'Message #2 from Foo')).toBe(true);
// This just proves that I am listening to the event, not
// that it is being emitted and listened on.
//expect(wrp.vm.$ebus._events['msg-sen']).toBeFalsy();
//expect(wrp.vm.$ebus._events['msg-sent']).toBeTruthy();
});
});
<template>
<div>
<input
class="msg"
type="text"
v-model="msg"
@input="sendMsg">
<p class="display-msg" v-text="msg"></p>
</div>
</template>
<script>
export default {
data () {
return {
msg: ''
};
},
created () {
this.$ebus.$on('msg-sent', (data) => {
//console.info('Foo.created evt msg-sent: ', data);
})
},
methods: {
sendMsg () {
this.$ebus.$emit('msg-sent', this.msg);
}
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment