我面临的问题是,当我注入上下文时,我的测试是看到我在MahContext
中设置的默认上下文。我试过使用Shallow,我试过在值周围没有context
包装器的情况下使用,这没关系。浅的给了我一个空的物体,这很奇怪。我还尝试将childContextTypes: { mahContext: PropTypes.object }
添加到mount
的第二个参数中,而shallow
无效。
我的上下文(默认):
const MahContext= React.createContext({ id: 0, name: '' })
我的提供者:
const MahProvider = props => (
<MahContext.Provider value={props.value}>
{props.children}
</MahContext.Provider>
)
组件树(在app.js中):
<MahProvider value=({9, "Johnny Utah"})>
<ParentOfMahComponent />
</MahProvider>
要测试的组件:
class MahComponent extends Component {
...
async componentDidMount() {
// for my test, results in 0 and '', the defaults
// which causes my test to fail as there is a validity check
// following
const { id, name } = this.context
}
}
MahComponent.contextType = MahContext
我的测试:
const component = mount(
<MahComponent />,
{
context: {
id: 7,
name: "John Wick"
}
}
}