测试依赖于上下文存储的组件
Testing a component that depends on store from context
我在为依赖于从上下文传递下来的 redux 存储的组件设置测试时遇到问题...
我的应用程序有一个根组件,它为其子组件提供 redux 存储作为上下文:
import ApplicationStore from './app-store.js'
class Root extends Component {
getChildContext() {
return { store: ApplicationStore }
}
render(){...}
}
Root.childContextTypes = {
store: PropTypes.object,
};
我有一个依赖于商店的组件(从上下文传递下来):
class List extends Component {
render(){
const items = this.context.store.getState();
return items.map((_, i) => (
<div key={i}>{_.name}</div>
));
}
}
List.contextTypes = {
store: PropTypes.object,
};
所以我的问题是:如何将存储对象 "inject" 放入组件的上下文中?我必须 unmock(./app-store.js)
吗?此外,我怎样才能在商店里预装几个固定装置?
谢谢!
我知道这不能回答您的问题,但我想向您推荐有关上下文的 React.js 文档:
Most applications will never need to use context. Especially if you are just getting started with React, you likely do not want to use context. Using context will make your code harder to understand because it makes the data flow less clear. It is similar to using global variables to pass state through your application.
和
Do not use context to pass your model data through components. Threading your data through the tree explicitly is much easier to understand. Using context makes your components more coupled and less reusable, because they behave differently depending on where they're rendered.
如果你使用 props 将你的商店(或者甚至只是它的必需部分)传递给你的子组件,那么你的问题就已经解决了,因为在你的测试中,你可以简单地注入你的模拟或存根商店。
我在为依赖于从上下文传递下来的 redux 存储的组件设置测试时遇到问题...
我的应用程序有一个根组件,它为其子组件提供 redux 存储作为上下文:
import ApplicationStore from './app-store.js'
class Root extends Component {
getChildContext() {
return { store: ApplicationStore }
}
render(){...}
}
Root.childContextTypes = {
store: PropTypes.object,
};
我有一个依赖于商店的组件(从上下文传递下来):
class List extends Component {
render(){
const items = this.context.store.getState();
return items.map((_, i) => (
<div key={i}>{_.name}</div>
));
}
}
List.contextTypes = {
store: PropTypes.object,
};
所以我的问题是:如何将存储对象 "inject" 放入组件的上下文中?我必须 unmock(./app-store.js)
吗?此外,我怎样才能在商店里预装几个固定装置?
谢谢!
我知道这不能回答您的问题,但我想向您推荐有关上下文的 React.js 文档:
Most applications will never need to use context. Especially if you are just getting started with React, you likely do not want to use context. Using context will make your code harder to understand because it makes the data flow less clear. It is similar to using global variables to pass state through your application.
和
Do not use context to pass your model data through components. Threading your data through the tree explicitly is much easier to understand. Using context makes your components more coupled and less reusable, because they behave differently depending on where they're rendered.
如果你使用 props 将你的商店(或者甚至只是它的必需部分)传递给你的子组件,那么你的问题就已经解决了,因为在你的测试中,你可以简单地注入你的模拟或存根商店。