JestでTypeError: Cannot read property 'have' of undefinedが出てしまった時


JSのテストフレームワークのJestとテストユーティリティEnzymeで Reactの、とあるコンポーネントが子コンポーネントをもっているかどうかをテストするコードを書いていたら、テスト実行時に以下のエラーに遭遇した。

    TypeError: Cannot read property 'have' of undefined

      14 | 
      15 |   //
    > 16 |   expect(wrapper.find(Foo)).to.have.length(1)
         |   ^
      17 | })
      18 | 

      at Object.<anonymous> (src/App.test.js:16:3)

EnzymeのEnzyme - API Referenceをみても、to.have.という書き方が掲載されていたのに、haveがないと言われてしまうので調べて見た。

原因

結論からいうと、上記のメソッドはChainのアサーションの書き方で、自分はChaiを利用してなかった為に起こったものだった。

を良く見てなかったが、以下のような記述がある。

Enzyme is unopinionated regarding which test runner or assertion library you use, and should be compatible with all major test runners and assertion libraries out there. The documentation and examples for enzyme use mocha and chai, but you should be able to extrapolate to your framework of choice.

このドキュメントは、要するにアサーションライブラリとして mochaとchaiを利用しているため、Chaiのチェーン可能なメソッドで書かれていたのだった。

参考: Chai Assertion Library

したがって、自分が確認すべきドキュメントは こちらで以下のように書くべきであった。

expect(wrapper.find(Foo).length).toBe(1)

参考