Alexey Petrushin
Alexey Petrushin

Reputation: 1351

How to pass mocked executable schema to Apollo Client?

The Mocking example for Apollo GraphQL has the following code (see below).

The interesting thing is the last line - they create and execute the graphql query. But you usually need to create ApolloClient object. I can't figure out how to do that.

The ApolloClient expect the NetworkingInterface as an argument not the executable schema.

So, is there a way to create ApolloClient from the executable schema, without NetworkingInterface?

import { makeExecutableSchema, addMockFunctionsToSchema } from 'graphql-tools';
import { graphql } from 'graphql';

// Fill this in with the schema string
const schemaString = `...`;

// Make a GraphQL schema with no resolvers
const schema = makeExecutableSchema({ typeDefs: schemaString });

// Add mocks, modifies schema in place
addMockFunctionsToSchema({ schema });

const query = `
query tasksForUser {
  user(id: 6) { id, name }
}
`;

graphql(schema, query).then((result) => console.log('Got result', result));

Upvotes: 4

Views: 2228

Answers (2)

Cam Jackson
Cam Jackson

Reputation: 12294

In Apollo client v2, networkInterface has been replaced with link for the network layer (see the client docs here).

apollo-test-utils hasn't been updated for Apollo client v2, and based on conversations from github, it seems the current recommendation is to use apollo-link-schema:

import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { SchemaLink } from 'apollo-link-schema';
import { makeExecutableSchema, addMockFunctionsToSchema } from 'graphql-tools';
import { typeDefs } from './schema';

const schema = makeExecutableSchema({ typeDefs });
addMockFunctionsToSchema({ schema });

const graphqlClient = new ApolloClient({
  cache: new InMemoryCache(),
  link: new SchemaLink({ schema })
});

Then you just need to inject the client into whatever you're testing!

Upvotes: 6

stubailo
stubailo

Reputation: 6147

The following is lifted from a docs PR written by magbicaleman on GitHub, based on our blog post:

You can easily do this with the apollo-test-utils, like so:

import { makeExecutableSchema, addMockFunctionsToSchema } from 'graphql-tools';
import { mockNetworkInterfaceWithSchema } from 'apollo-test-utils';
import { typeDefs } from './schema';

// Create GraphQL schema object
const schema = makeExecutableSchema({ typeDefs });

// Add mocks
addMockFunctionsToSchema({ schema });

// Create network interface
const mockNetworkInterface = mockNetworkInterfaceWithSchema({ schema });

// Initialize client
const client = new ApolloClient({
  networkInterface: mockNetworkInterface,
});

Now you can use the client instance as normal!

Upvotes: 8

Related Questions