为单击时调用的功能编写测试

时间:2019-01-23 11:07:38

标签: reactjs jestjs enzyme

我一直在尝试为自己构建的React组件编写一些测试。该组件实质上是在单击某个按钮(这是另一个组件)时将值传递到其容器中。

import PropTypes from 'prop-types';
import Button from '../../common/components/Button';
import Input from '../../common/components/Input';
import classNames from 'classnames';

class AddNewCellInputs extends React.Component {

  state = { value: '', shortName: '' }

  onChange = (e) => {
    let value = e.target.value;
    this.setState({ value: value })
  }

  onShortNameChange = (e) => {
    let shortName = e.target.value;
    this.setState({ shortName: shortName })
  }

  onAddCellSubmit = () => {
    const { value, shortName } = this.state
    this.props.onAddCellSubmit(shortName, value)
    this.setState({ value: '', shortName: '' })

  }


  render() {
    const { active, onNewCellClick } = this.props;
    const { value, shortName } = this.state
    return (
      <form className={classNames('csm__add-cell-form ', { 'active': active })}>
        <h3>Enter Cell Name</h3>
        <Input type="text" className="csm-modal-form__text-input" value={value} onChange={(e) => this.onChange(e)} />
        <Input type="text" className="csm-modal-form__text-input" value={shortName} onChange={(e) => this.onShortNameChange(e)} />

        <div className="csm__add-cell-form--button-container">
          <Button buttonClass="button-primary csm__button-add-cell" handleClick={() => this.onAddCellSubmit(shortName, value)} text="Add Cell" />
          <Button buttonClass="button-primary cancel" handleClick={onNewCellClick} text="Cancel" />
        </div>
      </form>
    );
  }

}

export default AddNewCellInputs;

};

这是测试

it('renders Call the addCellubmitMethod on lick of hte add-cell button', () => {
  const props = {
    active: true,
    onAddCellSubmit
  };
  let wrapper = mount(<AddNewCellInputs {...props} />);
  const onAddCellSubmit = jest.fn();
  wrapper.find('button').first().simulate('click');
  expect(onAddCellSubmit).toHaveBeenCalled();

});

这是我得到的错误

未捕获[TypeError:_this.props.onAddCellSubmit不是函数]。

我是测试新手,如果我做错了什么,请原谅我

1 个答案:

答案 0 :(得分:0)

您可以尝试这样。...

it('renders Call the addCellubmitMethod on lick of hte add-cell button', () => {
  const props = {
    active: true,
    onAddCellSubmit
  };
  let wrapper = mount(<AddNewCellInputs {...props} />);
  const onAddCellSubmitSpy = jest.spyOn(wrapper.instance(),'onAddCellSubmit');
  wrapper.find('button').first().prop('handleClick')();
  expect(onAddCellSubmitSpy).toHaveBeenCalled();
});