Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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));
like image 971
Alexey Petrushin Avatar asked Dec 08 '22 18:12

Alexey Petrushin


1 Answers

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!

like image 66
stubailo Avatar answered Jan 31 '23 08:01

stubailo