代码之家  ›  专栏  ›  技术社区  ›  crowhill

酶Shallow()和AddEventListener

  •  1
  • crowhill  · 技术社区  · 6 年前

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

    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 回复  |  直到 6 年前
        1
  •  1
  •   Danziger    6 年前

    正如你所看到的 in the docs ,ShallowWrapper API没有 ref() 方法,但您可以使用 mount() 取而代之的是 does have the ref() method .