0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2019-12-27

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)

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?