我正在尝试测试一个从根组件继承上下文的组件,而不需要从根组件加载/渲染所有内容。我尝试并搜索了有关如何模拟上下文的示例,但没有找到任何东西(至少没有使用jest)。
下面是我想要实现的一个简化示例。
有没有一种简单的方法可以让我模拟reactEl.context进行测试?
/**
* Root Element that sets up & shares context
*/
class Root extends Component {
getChildContext() {
return {
language: { text: 'A String'}
};
}
render() {
return (
<div>
<ElWithContext />
</div>
);
}
}
Root.childContextTypes = { language: React.PropTypes.object };
/**
* Child Element which uses context
*/
class ElWithContext extends React.Component{
render() {
const {language} = this.context;
return <p>{language.text}</p>
}
}
ElWithContext.contextTypes = { language: React.PropTypes.object }
/**
* Example test where context is unavailable.
*/
let el = React.createElement(ElWithContext)
element = TestUtils.renderIntoDocument(el);
// ERROR: undefined is not an object (evaluating 'language.text')
describe("ElWithContext", () => {
it('should contain textContent from context', () => {
const node = ReactDOM.findDOMNode(element);
expect(node.textContent).to.equal('A String');
});
})
发布于 2016-03-22 10:59:18
我选择了创建一个带有上下文的包装组件的解决方案。我不确定这是不是一个很好的方法,但现在对我来说是有效的:
/**
* Helper function to wrap component with a component that has context
*/
function wrapWithContext(context, contextTypes, children, React){
const wrapperWithContext = React.createClass({
childContextTypes: contextTypes,
getChildContext: function() { return context },
render: function() { return React.createElement('div', null, children) }
});
return React.createElement(wrapperWithContext);
}
/**
* Usage
*/
// in setup function of test framework
const el = React.createElement(ElWithContext);
const context = { language: { text: 'A String' } };
const contextTypes = { language: React.PropTypes.object };
const wrapper = wrapWithContext(context, contextTypes, [el], React);
const ElWithContext = TestUtils.renderIntoDocument(wrapper);
// do tests
describe('ElWithContext', () => {
it('should contain textContent from context', () => {
const node = ReactDOM.findDOMNode(element);
expect(node.textContent).to.equal('A String');
});
})
https://stackoverflow.com/questions/36143925
复制相似问题