简体   繁体   English

为什么在React单元测试中的模拟事件中使用sinon.spy模拟函数和React Component的asen.shallow渲染时,这是未定义的?

[英]Why is this is undefined when mocking event in React unit testing, using sinon.spy to mock function and enzyme.shallow render for React Component?

Whenever I try to simulate an event where I am passing the event object, I am getting that this is undefined . 每当我尝试模拟在那里我传递一个事件, event对象,我得到的是thisundefined

const onBlur = sinon.spy(Input.prototype.handleBlur);
const wrapper = shallow(<Input handleBlur={onBlur} />);
//...
wrapper.find('input').simulate('blur', { target: {value: ''} });

Inside of the handleBlur method, this is undefined. handleBlur方法内部, this是未定义的。 However, if I decide not to mock the event object, then event is undefined. 但是,如果我决定不模拟event对象,则事件未定义。

Also, I tried using mount instead: const wrapper = shallow(<Input handleBlur={onBlur} />); 另外,我尝试使用mount代替: const wrapper = shallow(<Input handleBlur={onBlur} />); But, it's the same thing. 但是,这是同一回事。 However, I couldn't even get to that point until I updated the npm libraries. 但是,直到更新npm库,我什至无法理解这一点。

try using 尝试使用

const onBlur = sinon.spy(Input.prototype, "handleBlur");

instead 代替

const onBlur = sinon.spy(Input.prototype.handleBlur);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM