【问题标题】:Passing a full `event` object in Enzyme simulate function在酶模拟函数中传递完整的“事件”对象
【发布时间】:2020-03-26 15:41:52
【问题描述】:

我目前正在使用 Jest 和 Enzyme 测试 React TextArea 组件。这个组件基本上只是一个原生 <textarea> 元素的包装器。它的行为是它会根据其当前值相对于集合max-height 自动调整其高度。这是 onchange 事件处理程序:

handleInputChange = e => {
    const { onChange } = this.props;
    const field = e.target;

    field.style.height = 'inherit';
    field.style.height = `${field.scrollHeight}px`;

    const max = parseInt(
      window.getComputedStyle(field).getPropertyValue('max-height'),
      10
    );

    field.style.overflowY = max < field.scrollHeight ? 'scroll' : 'hidden';

    if (onChange) {
      onChange(e);
    }
};

我想为它写一个单元测试,这样我就可以测试它是否更新了它的高度。我已经对如何将 onchange 事件模拟到输入进行了一些研究,但到目前为止我所看到的是它可以通过传递“部分填充”event 对象(它只有一个值属性)来完成,例如这个:

const spy = jest.spyOn(wrapper.instance(), 'handleInputChange');
const controlledTextArea = findByTestAttr(wrapper, 'controlledTextArea');
controlledTextArea.simulate('change', {
   target: {
     value: 'This is just for test'
   }
});

但这会导致错误,因为我需要访问e.targetstyle 属性。

所以我的问题是,我如何模拟一个 onchange 事件,就好像有一个正常的事件对象一样。我希望我能做这样的事情:

controlledTextArea.simulate('change', 'This is another test text');

然后它会自动为我创建event 对象。有没有办法做到这一点?

【问题讨论】:

    标签: reactjs jestjs enzyme


    【解决方案1】:

    实现这一目标并不容易。此外jest 在后台使用jsdom。它并没有实现浏览器所拥有的所有 API。 此外,当您在隔离中测试您的组件时,getComputedStyle 将无法访问所有原始 CSS,因此不会返回任何内容。

    总结以上所有内容,您必须同时模拟 target.stylewindow.getComputedStyle。可能类似:

    const target = {
      value: "change",
      style: {},
      scrollHeight: 1000,
    };
    jest.spyOn(window, 'getComputedStyle').mockImplementation((el) => {
      if (el === target) {
        return {
          "max-height": 200,
          getPropertyValue(propName) {
            return this[propName];
          }
        };
      }
    });
    
    yourWrapper.onChange({ target });
    expect(target.style.overflowY).toEqual('scroll');
    

    【讨论】:

      猜你喜欢
      • 2017-10-10
      • 2017-03-04
      • 2016-12-21
      • 2018-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多