Skip to content

Instantly share code, notes, and snippets.

@robrichard
Created November 1, 2017 16:40
Show Gist options
  • Select an option

  • Save robrichard/ad838e599d828a89978f54faaa2070a8 to your computer and use it in GitHub Desktop.

Select an option

Save robrichard/ad838e599d828a89978f54faaa2070a8 to your computer and use it in GitHub Desktop.

Revisions

  1. robrichard created this gist Nov 1, 2017.
    70 changes: 70 additions & 0 deletions react-relay.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,70 @@
    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;

    function makeRelayWrapper(relayProps) {
    return function (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;