用jest测试Relay [createFragmentContainer]?

时间:2017-08-21 17:39:29

标签: reactjs unit-testing react-native jestjs

我要测试我的组件,但是每个导出createFragmentContainer的组件都会向我显示这个问题:

console.error node_modules\react-native\Libraries\Core\ExceptionsManager.js:73
      Warning: Failed context type: Invalid prop/context `relay` supplied to `Relay(Product)`, expected `undefined` to be an object with an `environment` and `variables`.
          in Relay(Product)
    console.error node_modules\react-native\Libraries\Core\ExceptionsManager.js:73
      React caught an error thrown by Relay(Product). You should fix this error in your code. Consider adding an error boundary to your tree to customize error handling behavior.

      TypeError: Cannot read property 'environment' of undefined

      The error is located at:
          in Relay(Product)

jest是否支持片段容器或问题出在我的项目中?

1 个答案:

答案 0 :(得分:1)

将以下内容添加到__mocks__文件夹中。然后在测试中将jest.mock('react-relay');添加到需要中继的单元测试中。

import React from 'react';
import PropTypes from 'prop-types';

const relayMock = jest.genMockFromModule('react-relay');

const relayChildContextTypes = {
  relay: PropTypes.object,
};

const relayEnvironment = {
  lookup: jest.fn(),
};

const relayContext = {
  relay: {
    environment: relayEnvironment,
    variables: {},
  },
};

const relayFragmentProps = {
  relay: {
    environment: relayEnvironment,
  },
};

const relayRefetchProps = {
  relay: {
    environment: relayEnvironment,
    refetch: jest.fn(),
  },
};

const relayPaginationProps = {
  relay: {
    environment: relayEnvironment,
    hasMore: jest.fn(),
    loadMore: jest.fn(),
    isLoading: jest.fn(),
  },
};

relayMock.__relayEnvironment = relayEnvironment;
relayMock.__relayFragmentProps = relayFragmentProps;
relayMock.__relayRefetchProps = relayRefetchProps;
relayMock.__relayPaginationProps = relayPaginationProps;

const makeRelayWrapper = (relayProps) => (
  (Comp) => {
    class HOC extends React.Component {
      getChildContext() {
        return relayContext;
      }

      render() {
        return <Comp {...this.props} {...relayProps}/>;
      }
    }

    HOC.childContextTypes = relayChildContextTypes;
    return HOC;
  }
);

relayMock.QueryRenderer = jest.fn(() => React.createElement('div', null, 'Test'));

relayMock.createFragmentContainer = makeRelayWrapper(relayFragmentProps);
relayMock.createRefetchContainer = makeRelayWrapper(relayRefetchProps);
relayMock.createPaginationContainer = makeRelayWrapper(relayPaginationProps);

module.exports = relayMock;