首页 > 解决方案 > TypeError:无法读取 null 的属性“componentDidMount”

问题描述

我想断言在我的componentDidMount生命周期中使用正确的道具调用了一个方法。

  componentDidMount () {
    const { fetchContentForUser } = this.props
    fetchContentForUser({ userId: '6ae42468-83f2-0bf39a917713' })
  }

我的测试看起来像这样

let props
let wrapper
      beforeEach(() => {
        props = {
          fetchContentForUser: jest.fn(),
          loading: false
        }
      })

          it('should call fetchContentForUser on mount', () => {
            wrapper = shallow(<LandingComponent {...props} />)
            wrapper.update()
            wrapper.instance().componentDidMount()

            expect(props.fetchContentForUser).toHaveBeenCalled()
          })

但是我收到了错误

TypeError: Cannot read property 'componentDidMount' of null

我怎样才能断言这个方法被调用?我正在使用 Jest / Enzyme。

标签: reactjsjestjsenzyme

解决方案


推荐阅读