酶shallow()和addEventListener

时间:2018-11-30 21:53:04

标签: javascript reactjs enzyme

我有这个组件,在应用程序中可以正常工作

class TheComponent extends Component {

  componentDidMount() {
    this.watchForClicks();
  }

  watchForClicks() {
    this.elementRef.addEventListener('click', () => {
      console.log('there went one!');
    });
  }

  render() {
    return (
      <div
        ref={theElement => {
          this.elementRef = theElement;
        }}
      >
        ...
      </div>
    );
  }
}

export default TheComponent;

此测试:

describe('<TheComponent />', () => {
  context('do a test:', function() {
    it.only('fails!', () => {
      wrapper = shallow(<TheElement />)
    })
  });
});

为什么会出现此错误?

undefined is not an object (evaluating 'this.elementRef.addEventListener')

1 个答案:

答案 0 :(得分:1)

您可以看到in the docs,ShallowWrapper API没有ref()方法,但是您可以使用mount(),即does have the ref() method