Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Relay [createFragmentContainer] with jest?

I am tring to test my components but every component that exports createFragmentContainer shows me this issue:

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)

so does jest support fragment containers or the problem is in my project ?

like image 593
FrankenStein Avatar asked Aug 21 '17 17:08

FrankenStein


1 Answers

Add the below to __mocks__ folder. Then in the test add jest.mock('react-relay'); to the unit test that needs 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;
like image 93
s.Lawrenz Avatar answered Sep 25 '22 00:09

s.Lawrenz