如何在本机反应中模拟上下文消费者反应元素
Posted
技术标签:
【中文标题】如何在本机反应中模拟上下文消费者反应元素【英文标题】:How to mock a context consumer React element in react native 【发布时间】:2019-09-05 22:07:40 【问题描述】:我还没有找到任何证据表明任何人以前能够解决和解决这个问题。我有一个使用上下文的反应原生组件,我想渲染该组件。
// ThemeContext.js
import React from 'react';
export const ThemeContext = React.createContext(
color: 'white'
);
// MyText.js
import React, PureComponent from 'react';
import PropTypes from 'prop-types';
import Text from 'react-native';
export class MyText extends PureComponent
static propTypes =
children: PropTypes.node.isRequired
;
static defaultProps = ;
render()
let text = this.props.children;
return (
<Text>
text
</Text>
);
;
// MyText.test.js
import React from 'react';
import MyText from "../MyText";
import ThemeContext from '../ThemeContext';
describe('MyText', () =>
it('should render component', () =>
const wrapper = renderer.create(
<ThemeContext.Provider value=mobileColorThemes.standard>
<ThemeContext.Consumer>
(theme) => <MyText>abc</MyText>
</ThemeContext.Consumer>
</ThemeContext.Provider>
);
expect(wrapper).toMatchSnapshot();
);
);
但是当我用 jest 运行测试文件时,
jest text/__tests__/MyText.test.js
我收到以下错误
Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
at invariant (node_modules/fbjs/lib/invariant.js:42:15)
at createFiberFromElementType (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:1933:5)
at createFiberFromElement (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:1878:15)
at reconcileSingleElement (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:3334:19)
at reconcileChildFibers (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:3433:35)
at reconcileChildrenAtPriority (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:4091:30)
at reconcileChildren (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:4074:5)
at updateHostRoot (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:4268:9)
at beginWork (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:4563:16)
at performUnitOfWork (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:6529:16)...
jest 是否适用于 react native 和 context?世界上有没有人让这个工作? 使用 jest v24.1.0,react-native 0.56,react-test-renderer 16.0.0
【问题讨论】:
【参考方案1】:react
和 react-test-renderer
具有匹配的版本。由于在 React 16.3 中引入了上下文 API,预计 react-test-renderer@16.0.0
不支持 <Provider>
元素。
react-test-renderer
应该与react
具有相同的版本约束。
【讨论】:
谢谢你救了我!以上是关于如何在本机反应中模拟上下文消费者反应元素的主要内容,如果未能解决你的问题,请参考以下文章
R Shiny:如何使多个元素在添加/删除按钮上下文中具有反应性?