Sinon Spy + ReactJs 属性 初始化语法
Sinon Spy + ReactJs property initializers syntax
我正在尝试使用 Enzyme + Sinon spies 测试 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 函数,尽管据我所知,由于上下文绑定到实例而不是原型上的 属性,我无法监视就可以了。
我知道该函数被调用,我知道我可以通过将我的语法修改为标准 属性 样式来使间谍正常工作。我也知道组件的已安装实例具有 属性.
的方法
这是两者不能一起工作的情况之一,还是有我没看到的技巧?
Edit:这是我尝试建议的解决方案的方法,但是 spy.calledOnce returns false spy.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
的原型方法更可取 ,它们可以在 class 实例化之前被监视或模拟。这对于在构造函数或初始生命周期挂钩中调用的方法很重要。
handleMouseOver
显然是在组件实例化后触发的事件处理程序,因此只要组件实例可通过 Enzyme 访问,它就可以被侦测到。设置间谍后需要重新渲染组件,以便 <button>
接收新的事件处理程序。有 a bug with Enzyme 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);
我正在尝试使用 Enzyme + Sinon spies 测试 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 函数,尽管据我所知,由于上下文绑定到实例而不是原型上的 属性,我无法监视就可以了。
我知道该函数被调用,我知道我可以通过将我的语法修改为标准 属性 样式来使间谍正常工作。我也知道组件的已安装实例具有 属性.
的方法这是两者不能一起工作的情况之一,还是有我没看到的技巧?
Edit:这是我尝试建议的解决方案的方法,但是 spy.calledOnce returns false spy.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>
接收新的事件处理程序。有 a bug with Enzyme 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);