6
4

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.

reduxの@connectをデコレーター構文そのままにテストする(webpackの場合)

Last updated at Posted at 2016-01-09

問題

react-reduxの@connectが定義された要素をテストしようとすると、
以下の様なエラーになって実行する事が出来ません。

// こんな感じのクラス
@connect
export defautl class Hoge() {
}

Invariant Violation: Could not find "store" in either the context or props of "Connect(Login)". Either wrap the root component in a , or explicitly pass "store" as a prop to "Connect(Login)".

対策(公式)

これはリファレンスのWriting Testsでも言及されていて、
decoratorを外して、connectされていないオブジェクトをテストする事を推奨されています。

// In order to be able to test the App component itself without having to deal with the decorator,
// we recommend you to also export the undecorated component:

import { connect } from 'react-redux'

// Use named export for unconnected component (for tests)
export class App extends Component { /* ... */ }

// Use default export for the connected component (for app)
export default connect(mapDispatchToProps)(App)

# 上記の例であればclass Appに対してテストする

反論

いや、せっかくのdecorator構文を外したくないです。
テストの為にプロダクトコードを改変する事は必要な場合もあると承知していますが、これはちょっとイヤです。

結論

というわけで、webpackを使っているので手っ取り早くexternalを使って逃げます。

私の場合はkarma.config.babel.jswebpack.externalsを以下のように弄ります。

    externals: [
      {
        "react-redux": "{ connect: (con) => con }"
      }
    ]

ちゃんとmock化してもいいのですが、react-reduxのAPIはProviderとconnectしかないのでとりあえずはこれで満足です。

以上です。

6
4
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
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?