首页 > 解决方案 > TypeError:e.persist 不是 Typeahead Bootstrap React 中的函数

问题描述

尝试尝试不同的方法在 Enzyme 中测试我的应用程序时出现错误TypeError: e.persist is not a function,但似乎没有任何效果。

input.prop('onChange')({target: {value: "valuehere", name: "namehere", placeholder: "placeholderhere"}});

input.simulate('change', { target: {value: "valuehere", name: "namehere", placeholder: "placeholderhere"}});

input.props().onChange( {target: {value: "valuehere", name: "namehere", placeholder: "placeholderhere"}});

我的代码是:

import {Typeahead} from 'react-bootstrap-typeahead';
import 'react-bootstrap-typeahead/css/Typeahead.css';

export interface InputFormProps {
    label: string;
    id: string;
    icon: string;
    input: any;
    value: string[];
}

export default class InputForm extends React.Component<InputFormProps> {

  state = {
    value: this.props.value, list: []
   }


  async componentDidMount() {
    // API Calls happen here, not relevant
  }


  change = (value, label) => {
        //Converts to a form that the upper function understands from events
        let result = { target: {value, placeholder: label}};
        this.props.input(result);
      }

  render () {


    //Doesn't render list unless it has loaded

    return(
        <Typeahead
          multiple
          selected={this.props.value}
          name={this.props.label}
          type="text"
          className="form-control"
          placeholder={this.props.label}
          id={this.props.id}
          onChange={e => this.change(e, this.props.label)}
          options={this.state.list}/>
    )

  }

}

请注意,某些值已更改以保护我公司工作的隐私。

标签: react-bootstrap-typeahead

解决方案


该库似乎在事件对象中使用了其他功能/属性。如果您的测试不依赖于它在浏览器中的工作方式,您可以使用以下内容删除使用的内容:

input.prop('onChange')({
  persist: jest.fn(),
  target: { value: "valuehere", name: "namehere", placeholder: "placeholderhere" }
});

推荐阅读