首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >react-test-renderer如何创建带有上下文的组件?

react-test-renderer如何创建带有上下文的组件?
EN

Stack Overflow用户
提问于 2018-01-07 01:12:05
回答 1查看 2.4K关注 0票数 2

react-test-render的Api表示:

TestRenderer.create(元素,选项);

create的有效选项是什么?我可以用它来设置组件的上下文吗?

https://reactjs.org/docs/test-renderer.html#reference

EN

回答 1

Stack Overflow用户

发布于 2018-05-03 04:59:41

context接口不支持直接设置context- check out the create implementation here

您可以创建一个简单的包装器,只传递上下文:

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

https://stackoverflow.com/questions/48129799

复制
相关文章

相似问题

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