example VueJs Testing: bound-to-template method
by Mohannad Najjar
HTML
<link rel="stylesheet" href="//cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.css">
<script src="//cdn.rawgit.com/jquery/jquery/2.1.4/dist/jquery.min.js"></script>
<script src="//cdn.rawgit.com/Automattic/expect.js/0.3.1/index.js"></script>
<script src="//cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/sinon.js/4.0.2/sinon.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script>
<div id="mocha"></div>
JavaScript
let Ctor = Vue.component('demo', {
template: `<div>
<button id="save-btn" @click="save">Save Me!</button>
<button id="save-btn2" @click="save()">Save Me!</button>
<button id="cancel-btn" @click="cancel">Cancel!</button>
</div>`,
data: {},
methods: {
save() {},
cancel() {
this.cancelAction()
},
cancelAction() {}
}
})
mocha.setup('bdd')
describe('Sinon & Vue event handlers', () => {
it("sinon can't spy on event handler methods bounded by the name only in the template", () => {
const vm = new Ctor().$mount()
sinon.spy(vm, 'save')
vm.$el.querySelector('#save-btn').click()
expect(vm.save.called).to.equal(false)
})
it('sinon can spy on inline event handler methods bounded as a js statement in the template', () => {
const vm = new Ctor().$mount()
sinon.spy(vm, 'save')
vm.$el.querySelector('#save-btn2').click()
expect(vm.save.called).to.equal(true)
})
it('sinon can spy on methods', () => {
const vm = new Ctor().$mount()
sinon.spy(vm, 'cancelAction')
vm.$el.querySelector('#cancel-btn').click()
expect(vm.cancelAction.called).to.equal(true)
})
})
mocha.checkLeaks()
mocha.globals(['jQuery'])
mocha.run()