反应测试渲染的Api说:
TestRenderer.create(element,options);
创建的有效选项有哪些? 我可以用它来设置组件的上下文吗?
答案 0 :(得分:1)
TestRenderer
API不支持直接设置上下文 - check out the create
implementation here。
您可以创建一个只传递上下文的简单包装器:
import React from 'react'
import TestRenderer from 'react-test-renderer'
import PropTypes from 'prop-types'
// The example component under test
export default class WithContext extends React.Component {
static contextTypes = {
someProperty: PropTypes.any,
}
render () {
return (
<div>{ this.context.someProperty }</div>
)
}
}
describe('<WithContext>', () => {
it('renders the supplied context', () => {
const tree = TestRenderer.create(
<PassContext value={{ someProperty: 'context' }}>
<WithContext />
</PassContext>
)
tree.root.find(findInChildren(node =>
typeof node === 'string' &&
node.toLowerCase() === "context"
))
});
});
class PassContext extends React.Component {
static childContextTypes = {
someProperty: PropTypes.any,
}
getChildContext () {
return this.props.value
}
render () {
return this.props.children
}
}
// Returns a TestInstance#find() predicate that passes
// all test instance children (including text nodes) through
// the supplied predicate, and returns true if one of the
// children passes the predicate.
function findInChildren (predicate) {
return testInstance => {
const children = testInstance.children
return Array.isArray(children)
? children.some(predicate)
: predicate(children)
}
}