【问题标题】:Testing Relay [createFragmentContainer] with jest?用玩笑测试 Relay [createFragmentContainer]?
【发布时间】:2018-01-29 20:47:41
【问题描述】:

我正在尝试测试我的组件,但是导出 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 是否支持片段容器或者问题出在我的项目中?

【问题讨论】:

标签: reactjs unit-testing react-native jestjs


【解决方案1】:

将以下内容添加到__mocks__ 文件夹。然后在测试中将jest.mock('react-relay');添加到需要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;

【讨论】:

  • 如果可以在答案中添加 sn-ps 代码,请尽量不要链接到外部资源(这使得答案在 URL 内容被删除的情况下不会过时)。
  • 明白了。更新
猜你喜欢
  • 2021-02-10
  • 2020-07-31
  • 1970-01-01
  • 2019-02-22
  • 2020-11-14
  • 1970-01-01
  • 2017-11-29
  • 2020-07-04
  • 2020-06-30
相关资源
最近更新 更多