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

时间:2017-04-06 04:17:28

标签: graphql react-apollo

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

有趣的是最后一行 - 他们创建并执行graphql查询。但是你通常需要创建ApolloClient对象。我无法弄清楚如何做到这一点。

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

那么,有没有办法从可执行模式创建ApolloClient,而没有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));

2 个答案:

答案 0 :(得分:8)

以下内容取自magbicaleman在GitHub上根据我们的docs PR编写的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,
});

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

答案 1 :(得分:5)

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

apollo-test-utils尚未针对Apollo客户端v2进行更新,并且基于来自github的conversations,目前的建议似乎是使用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 })
});

然后,您只需将客户端注入您正在测试的任何内容中!