当作为事件的回调调用时,Sinon spies 如何注册一个被调用的 Vue 组件方法? [英] How can Sinon spies register a Vue component method as called when it is called as an event's callback?

查看:22
本文介绍了当作为事件的回调调用时,Sinon spies 如何注册一个被调用的 Vue 组件方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 vue 组件中有一个名为 testfn 的方法,每当 testevt 事件触发时都会调用该方法.此方法包含对 console.log 的调用,清楚地显示正在调用该方法.

I have a method called testfn in my vue component that gets called whenever event testevt fires. This method contains a call to console.log that clearly shows the method is being called.

使用vue-test-utils运行测试时,如果我为该方法创建了Sinon spy并直接调用该方法,该spy正确检测到该方法被调用:

When running a test with vue-test-utils, if I create a Sinon spy for the method and call the method directly, the spy correctly detects that the method was called:

const wrapper = mount(MyComponent, {});
var spy = sinon.spy(wrapper.vm, 'testfn');
wrapper.vm.testfn();
expect(spy.called).to.be.true; //(uses the Chai assertion library)

这不会引发错误.但是,如果我创建相同的 spy,但不是直接调用该方法,而是发出调用我的方法的事件,该方法将被调用(我可以看到这一点,因为该方法包含对 console.log 的调用)但 spy 确实如此不注册该方法被调用.因此,以下给出了错误:

This does not throw an error. However, if I create the same spy, but instead of calling the method directly, I emit the event that calls my method, the method gets called (I can see this because the method contains a call to console.log) but the spy does not register that the method was called. Thus, the following gives an error:

const wrapper = mount(MyComponent, {});
var spy = sinon.spy(wrapper.vm, 'testfn');
wrapper.vm.$emit('testevt');
expect(spy.called).to.be.true; //(uses the Chai assertion library)

似乎正在发生的事情是没有调用 testfn 本身,而是调用了它的一个克隆.无论如何,如何使用 sinon 间谍来检测在发出 testevt 事件后是否调用了 testfn 或其克隆?

What seems to be happening is that testfn itself is not called, but rather, a clone of it is called. Regardless, how can I use a sinon spy to detect whether testfn, or a clone of it, gets called after I emit the testevt event?

推荐答案

我今天尝试过这样的间谍活动但没有成功,所以我切换到:

I was trying spying like that today with no success so I switched to:

const spy = sinon.spy()
const wrapper = shallowMount(MyComponent, {localVue, methods: {clicked: spy}})
wrapper.get('button').trigger('click')
expect(spy).to.have.been.calledOnce

希望有人能找到真正的答案 - 但在此之前这是有效的.

Hopefully someone can find an actual answer - but until then this works.

这篇关于当作为事件的回调调用时,Sinon spies 如何注册一个被调用的 Vue 组件方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆