继电器现代:如何模拟继电器进行单元测试

时间:2017-08-26 16:23:56

标签: react-native relaymodern

我试图测试反应继电器现代容器,但我遇到了这个问题。

TypeError: Cannot read property 'environment' of undefined

这是测试代码:

test('render component', () => {
  const tree = renderer.create(
    <User />,
  ).toJSON();

  expect(tree).toMatchSnapshot();
});

2 个答案:

答案 0 :(得分:0)

你实际上根本不需要模拟环境变量。我通常做的是添加:

export class User

到我要测试的类的classdeclaration。 (确保将导出默认值保留在同一类的已连接版本上)。

然后,我可以通过导入组件来测试组件的首选方式,而不需要在我的测试中进行中继:

 import { User } from '../User'

这消除了对模拟中继的需要,您可以将道具干净地传递给组件。

答案 1 :(得分:-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;