2017-04-06 23 views
3

Apollo GraphQL的模拟示例具有以下代码(请参见下文)。如何将模拟的可执行模式传递给Apollo客户端?

有趣的是最后一行 - 它们创建并执行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)); 
+0

有一个开放的公关文档,我仍然需要合并:https://github.com/apollographql/react-docs/pull/172 – stubailo

回答

8

从GitHub上写的magbicaleman一个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, 
}); 

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

+0

谢谢,虽然它看起来太复杂了这样一个简单的用例。 .. –

+0

理想情况下,它应该像'新的ApolloClient({schema:executableSchema})' –

+2

我们并不试图优化代码行。在这种情况下,对于过程的每个部分都有一个具体的方法来做好一件事情。如果您愿意,您可以轻松编写一个帮助函数来制作这一行。 – stubailo

3

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

apollo-test-utils尚未阿波罗客户V2更新,并根据conversations从GitHub,似乎目前的建议是使用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 }) 
}); 

然后你只需要在客户端注入到任何你重新测试!

相关问题