Ale*_*hin 4 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));
Run Code Online (Sandbox Code Playgroud)
以下是基于我们的博客文章从GitHub上编写的文档PR中解除的:magbicaleman
您可以轻松地执行此操作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,
});
Run Code Online (Sandbox Code Playgroud)
现在您可以正常使用客户端实例!
在Apollo客户端v2中,networkInterface已经替换link为网络层(请参阅此处的客户端文档).
apollo-test-utils尚未针对Apollo客户端v2进行更新,并且基于来自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 })
});
Run Code Online (Sandbox Code Playgroud)
然后你只需要将客户端注入你正在测试的任何东西!
| 归档时间: |
|
| 查看次数: |
1911 次 |
| 最近记录: |