Sinon Spy+ReactJs属性初始化程序语法



我正在尝试用Enzyme+Sinon间谍测试React组件。我的react代码在我的组件实例中使用属性初始值设定项语法:

class FixedButton extends React.Component {
handleMouseOver = (e) => {
const { fixedButtonHover = _fixedButtonHover } = this.props;
const { backgroundColor, color } = fixedButtonHover;
e.target.style.backgroundColor = backgroundColor;
e.target.style.color = color;
}
}

我正试图弄清楚如何监视handleMouseOver函数,尽管据我所知,由于上下文与实例绑定,而不是原型上的属性,我无法监视它

我知道函数被调用了,我知道我可以通过将语法修改为标准属性样式来使间谍正常工作。我还知道组件的已安装实例具有作为属性的方法。

这是两种情况中的一种,还是我没有看到的技巧?

编辑:以下是我尝试建议的解决方案的方式,但spy.calledOnce间谍一样返回false。called:

test('FixedButton component methods are called as expected', t => {
const wrapper = mount(<FixedButton />);
const instance = wrapper.instance();
const spy = sinon.spy(instance, 'handleMouseOver');
const button = wrapper.find('button');
button.simulate('mouseover');
t.is(spy.calledOnce, true);
})

由于包括可测试性在内的几个原因,带有bind的原型方法是优选的,它们可以在类实例化之前被监视或模拟。这对于在构造函数或初始生命周期挂钩中调用的方法非常重要。

handleMouseOver显然是在组件实例化后触发的事件处理程序,所以只要组件实例可以通过Enzyme访问,就可以监视它。组件需要在设置间谍后重新渲染,以便<button>接收新的事件处理程序。酶update()有一个错误,需要解决:

const instance = wrapper.instance();
const spy = sinon.spy(instance, 'handleMouseOver');
instance.forceUpdate(); // necessary for button to receive proper handler
const button = wrapper.find('button');
button.simulate('mouseover');
t.is(spy.calledOnce, true);

最新更新