Skip to content

Latest commit

 

History

History
90 lines (75 loc) · 2.72 KB

README.md

File metadata and controls

90 lines (75 loc) · 2.72 KB

Deprecation notice

This functionality is now officially supported in Relay using the relay-test-utils package maintained by the Relay team. It is recommended to use that instead of this package.

relay-mock-network-layer

Provides a network layer for relay modern that returns schema-correct mock data using addMockFunctionsToSchema from graphql-tools;

This is useful for working in an environment like storybook where you want to work on your components without hitting a live GraphQL server.

Usage

import {
	Environment,
	Network,
	RecordSource,
	Store
} from 'relay-runtime';
import getNetworkLayer from 'relay-mock-network-layer';
import schema from './graphql.schema.json';

const network = Network.create(getNetworkLayer({
    schema,
    // pass custom mocks as documented in graphql-tools
    // http://dev.apollodata.com/tools/graphql-tools/mocking.html#Customizing-mocks
    mocks: {
        Geography: () => ({
            id: '2',
            countries: [{
                abbreviation: 'US',
                name: 'United States'
            }, {
                abbreviation: 'UK',
                name: 'United Kingdom'
            }],
                usStates: [{
                abbreviation: 'NY',
                name: 'New York'
            }, {
                abbreviation: 'NJ',
                name: 'New Jersey'
            }]
        }),
        Address: () => ({
            country: 'US',
            city: 'New York',
            state: 'NY',
            zipCode: '10012',
        })
    },

    // See https://www.apollographql.com/docs/graphql-tools/mocking.html#Mocking-interfaces
    preserveResolvers: false,

    // Forward along other options to `makeExecutableSchema`.
    ...schemaDefinitionOptions
}));

// Create an environment using this network:
const store = new Store(new RecordSource());
const environment = new Environment({network, store});

// use environment in <QueryRenderer>

Mocking custom scalar types

If your schema has custom scalar types you'll need to use the resolvers option to ensure those types get mocked correctly. Pass this option an object containing a resolve function for each custom scalar.

...
import getNetworkLayer from 'relay-mock-network-layer';
import {GraphQLScalarType} from 'graphql';

...

getNetworkLayer({
    schema,
    mocks: {...},
    resolvers: {
        CustomScalar: new GraphQLScalarType({
            name: 'CustomScalar',
            parseLiteral: () => {},
            parseValue: () => {},
            serialize: () => {}
        }),
        CustomScalar2: ...
    }
});