如何测试利用上下文API的RN组件

时间:2019-01-20 03:17:14

标签: reactjs react-native jestjs

我正在尝试测试this component

// click on "this component" to see the full code
export default class ButtonMain extends React.Component<ButtonMainProps, ButtonMainState> {
  render() {
    const gradient = this.props.theme === 'light' ?
      constants.themeLight.GRADIENT_MAIN :
      constants.themeDark.GRADIENT_MAIN;

    return (
      <Consumer>
        {
          ({ theme, toggleTheme }) =>
          <Link to={ this.props.to }>
            <View>
              <LinearGradient
                colors={ gradient }
                start={ [0, 0.5] }
                end={ [1, 0.5] }
                style={ styles.buttonMain }
              >
                <Text
                  style={ styles.buttonMain__text }
                  testID="buttonMain__text"
                >
                  { this.props.label.toUpperCase() }
                </Text>
              </LinearGradient>
            </View>
          </Link>
        }
      </Consumer>
    );
  }
}

使用此测试:

import * as React from 'react';
import ButtonMain from '../../../components/atoms/ButtonMain';
import { Provider } from '../../../Context';
import * as renderer from 'react-test-renderer';

class MockContainer extends React.Component {

  constructor(props) {
    super(props);

    this.toggleTheme = () => {
      this.setState(
        (prevState) => {
          return { theme: prevState.theme === 'light' ? 'dark' : 'light' };
        }
      );
    };

    this.state = {
      loadedAssets: false,
      theme: 'light',
      toggleTheme: this.toggleTheme,
    };
  }

  render() {
    return null;
  }
}


it('renders without crashing', () => {
  const rendered = renderer.create(
    <Provider value={ MockContainer.state }>
      <ButtonMain
        to="test-route"
        label="Test"
        theme="light"
      />
    </Provider>
    ).toJSON();
  expect(rendered).toBeTruthy();
});

NB:<MockContainer>试图反映<Provider> in the app 的结构。

但是,在运行测试时,我总是收到此错误:

    TypeError: Cannot read property 'theme' of undefined

      18 |       <Consumer>
      19 |         {
    > 20 |           ({ theme, toggleTheme }) =>
      21 |           <Link to={ this.props.to }>
      22 |             <View>
      23 |               <LinearGradient

我已经在Internet上搜索了信息,但是我发现的几乎所有内容都与ReactJS或不使用Context API的React Native组件有关。

对于解决此问题的任何想法,我将不胜感激! :)

0 个答案:

没有答案