如何在React Native中模拟上下文使用者React元素

时间:2019-04-15 21:22:17

标签: reactjs react-native jestjs react-context react-test-renderer

我还没有找到任何证据能够证明任何人以前能够解决这个问题。我有一个使用上下文的React本机组件,我想呈现该组件。

// 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 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 v24.1.0,react-native 0.56,react-test-renderer 16.0.0

1 个答案:

答案 0 :(得分:2)

reactreact-test-renderer具有匹配的版本。由于上下文API是在React 16.3中引入的,因此预计react-test-renderer@16.0.0不支持<Provider>元素。

react-test-renderer应该具有与react相同的版本约束。