vuejs2 - How to Sinon spy a Vue component method triggered by a Vue event? -
the basic setup i've done in order describe problem:
using vue-cli 2.8.2, generated new project based on webpack template (vue init webpack vue-test-sinon-spy
) keeping defaults of vue-cli (with irrelevant exception of disabling eslint).
changes done in vue-cli generated project:
- i attached event on h2 tag hello.vue:
<h2 @click="sayhello">essential links</h2>
- i added method in hello component
<script> export default { ... methods: { sayhello() { console.log('hello!') } } } </script>
- i added new test in hello.spec.js
describe('hello.vue', () => { // ... it('should handle click on h2 tag', () => { const constructor = vue.extend(hello) const vm = new constructor().$mount() sinon.spy(vm, 'sayhello') // [a] if run line below, vm.sayhello.callcount 0 - not expected vm.$el.queryselector('h2').click() // [b] if run line below, vm.sayhello.callcount 1 - expected // vm.sayhello() // vm.sayhello.callcount 0 or 1, depending on // line execute ([a] or [b]), // if in both cases sayhello method executed console.log('###', vm.sayhello.callcount) }) })
when programmatically click html tag (using vm.$el.queryselector('h2').click()
), spy won't capture execution of method sayhello
, vm.sayhello.callcount
0. not like.
but, if directly call sayhello
(using vm.sayhello()
), vm.sayhello.callcount
1. expect.
how can make spy capture call of sayhello
(so vm.sayhello.callcount
1), if want simulate click on html tag (vm.$el.queryselector('h2').click()
), , not directly calling sayhello
(no vm.sayhello()
)?
thanks
(note phil's comment on not being valid use of unit tests.)
a workaround found this:
install vue-test-utils:
yarn add --dev https://github.com/vuejs/vue-test-utils
(afaiu, vue-test-utils not officially released yet)trigger dummy click event
now, can add new test, run expected:
describe('hello.vue', () => { // ... it('should handle click on h2 tag - vue-test-utils + dummy click version', () => { const wrapper = mount(hello) sinon.spy(wrapper.vm, 'sayhello') // trigger dummy click event wrapper.find('h1').trigger('click') // [a] if run line below, vm.sayhello.callcount 1 - expected wrapper.find('h2').trigger('click') // [b] if run line below, vm.sayhello.callcount 1 - expected // wrapper.vm.sayhello() // vm.sayhello.callcount 1 in both [a] , [b] cases console.log('#####', wrapper.vm.sayhello.callcount) }) })
this behavior weird , make vue looks more pet project 2.x.x project, maybe misunderstood something.
Comments
Post a Comment