首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >React js -如何在测试组件时模拟上下文

React js -如何在测试组件时模拟上下文
EN

Stack Overflow用户
提问于 2016-03-22 08:02:44
回答 1查看 17.2K关注 0票数 28

我正在尝试测试一个从根组件继承上下文的组件,而不需要从根组件加载/渲染所有内容。我尝试并搜索了有关如何模拟上下文的示例,但没有找到任何东西(至少没有使用jest)。

下面是我想要实现的一个简化示例。

有没有一种简单的方法可以让我模拟reactEl.context进行测试?

代码语言:javascript
复制
/**
* 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');
  });
})
EN

回答 1

Stack Overflow用户

发布于 2016-03-22 10:59:18

我选择了创建一个带有上下文的包装组件的解决方案。我不确定这是不是一个很好的方法,但现在对我来说是有效的:

代码语言:javascript
复制
/**
* 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');
   });
})
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36143925

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档