【问题标题】: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?为什么在 React 单元测试中模拟事件时这是未定义的,使用 sinon.spy 模拟函数和酶.shallow 渲染 React 组件?
【发布时间】:2019-04-16 19:14:11
【问题描述】:

每当我尝试模拟传递event 对象的事件时,我都会得到thisundefined

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

handleBlur 方法内部,this 是未定义的。但是,如果我决定不模拟 event 对象,则事件未定义。

另外,我尝试使用 mount 代替: const wrapper = shallow(<Input handleBlur={onBlur} />); 但是,这是同一回事。但是,在更新 npm 库之前,我什至无法达到这一点。

【问题讨论】:

    标签: javascript reactjs unit-testing sinon enzyme


    【解决方案1】:

    尝试使用

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

    改为

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

    【讨论】:

      猜你喜欢
      • 2018-01-26
      • 2017-04-05
      • 2021-12-10
      • 1970-01-01
      • 1970-01-01
      • 2017-06-09
      • 1970-01-01
      • 2021-01-01
      • 2020-02-01
      相关资源
      最近更新 更多