【问题标题】:Testing input component with jest Enzyme用 jest Enzyme 测试输入组件
【发布时间】:2020-01-27 09:32:30
【问题描述】:

我有一个简单的 Input 组件,我想用酶来测试它。

import TextField from '@material-ui/core/TextField';
import React from 'react';

const TextComponent = (props) => {
  const handleInputChange = (name) => ({ target }) => {
    props.handleChange({ [name]: target.value }, target.value);
  };
  return (
    <TextField onChange={handleInputChange(props.name)} {...props} className="textComponent" />
  );
};

export default TextComponent;

我的测试用例是这样的

import React from 'react';
import { mount } from 'enzyme';
import { TextComponent } from '../../../tests';

test('<TextComponent> with label, name', () => {
  const onChangeMock = jest.fn();
  const handleChangeMock = jest.fn();
  const input = mount(
    <TextComponent
      label="Test"
      onChange={onChangeMock}
      value="test value"
      variant="outlined"
      name="testname"
      handleChange={handleChangeMock}
    />
  );
  expect(input.props().label).toEqual('Test');
  expect(input.props().name).toEqual('testname');
  expect(input.props().variant).toEqual('outlined');
  input.find('input').simulate('change');
  expect(handleChangeMock).toBeCalledWith({testname: 'test value'}, 'test value');
});

运行测试用例时出现错误提示

Warning: React does not recognize the `handleChange` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it
 as lowercase `handlechange` instead. If you accidentally passed it from a parent component, remove it from the DOM element.

如何测试我的 handleChangeMock 函数是否使用正确的数据调用?

【问题讨论】:

    标签: reactjs jestjs material-ui enzyme


    【解决方案1】:

    在您的测试中,这些道具被传递给TextComponent

    //...
          label="Test"
          onChange={onChangeMock}
          value="test value"
          variant="outlined"
          name="testname"
          handleChange={handleChangeMock}
    //...
    

    但是在TextComponent 实现中,所有这些道具在装饰handleChange 道具后都在MUITextField 中转发。

    <TextField onChange={handleInputChange(props.name)} {...props} className="textComponent" />
    

    handleChange 属性在被修饰并作为MUITextField 组件的onChange 属性传递后,需要在MUITextField 组件中被转发。

    这可以通过对象解构来完成。

    const TextComponent = (props) => {
      const {handleChange, ...restProps} = props;
      const handleInputChange = (name) => ({ target }) => {
        handleChange({ [name]: target.value }, target.value);
      };
      return (
        <TextField
            onChange={handleInputChange(props.name)} 
            {...restProps} 
            className="textComponent"
        />
      );
    };
    
    

    另外,在测试中省略 onChange 属性。它覆盖了 TextComponent 实现中的装饰 onChange 道具,因为 restProps 将包含另一个 onChange 道具。

    【讨论】:

      猜你喜欢
      • 2017-02-12
      • 2021-01-08
      • 2018-08-30
      • 2019-05-30
      • 2018-08-20
      • 1970-01-01
      • 2020-05-10
      • 2017-04-13
      • 2021-06-24
      相关资源
      最近更新 更多