如何将模拟的可执行模式传递给 Apollo Client?

How to pass mocked executable schema to Apollo Client?

A​​pollo GraphQL 的 Mocking 示例具有以下代码(见下文)。

有趣的是最后一行 - 他们创建并执行 graphql 查询。但是您通常需要创建 ApolloClient 对象。我不知道该怎么做。

A​​polloClient 期望 NetworkingInterface 作为参数而不是可执行模式。

那么,有没有办法在没有 NetworkingInterface 的情况下从可执行模式创建 ApolloClient?

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));

以下摘自docs PR written by magbicaleman on GitHub, based on our blog post

您可以使用 apollo-test-utils 轻松完成此操作,例如:

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,
});

现在您可以正常使用客户端实例了!

在 Apollo 客户端 v2 中,网络层的 networkInterface 已替换为 link(请参阅客户端文档 here)。

apollo-test-utils 尚未针对 Apollo 客户端 v2 进行更新,并且基于 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 })
});

然后你只需要将客户端注入你正在测试的任何东西!