問題
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.js
のwebpack.externals
を以下のように弄ります。
externals: [
{
"react-redux": "{ connect: (con) => con }"
}
]
ちゃんとmock化してもいいのですが、react-reduxのAPIはProviderとconnectしかないのでとりあえずはこれで満足です。
以上です。