对 apollo-ios 包的实用扩展。
我们很高兴能够使用 ApolloClientProtocol
,ApolloClient
符合该协议。但是,ApolloClient
的实现提供了 ApolloClientProtocol
没有提供的默认参数值。现在,可以将此视为一个非问题!
想要测试你应用中与 ApolloClient
相关的代码吗?那么 MockApolloClient
就是你的最佳选择!这个模拟对象符合 AppoloClientProtocol
,并且允许你为查询、变更和订阅提供存根响应。
func test_query() throws {
let apolloClient = MockApolloClient()
apolloClient.fetchResult = { parameters in
let data = TestQuery.Data(items: .init(edges: [
.init(node: .init(id: "1",name: "Brad")),
]))
return .success(GraphQLResult(data: data))
}
let expectation = expectation(description: #function)
apolloClient.fetch(query: TestQuery()) { result in
expectation.fulfill()
switch result {
case .success(let result):
XCTAssertEqual(result.data?.items.edges.count, 1)
XCTAssertEqual(result.data?.items.edges[0].node.id, "1")
XCTAssertEqual(result.data?.items.edges[0].node.name, "Brad")
case .failure(let error):
XCTFail("Unexpected error: \(error)")
}
}
wait(for: [expectation], timeout: 1.0)
}
想要使用你控制的稳定 JSON 数据来测试生成的 GraphQL 数据模型吗?GraphQLResult.mockedJSONResponse
可以解决你的问题!
模拟你的响应,例如你的应用程序包中的 items.json
{
"data": {
"items": {
"__typename": "ItemCollection",
"edges": [
{
"__typename": "ItemCollectionEdge",
"node": {
"__typename": "Item",
"id": "1",
"name": "Brad"
}
}
]
}
}
}
然后针对该模拟响应进行测试
func test_mockedJSONResponse() throws {
let url = try XCTUnwrap(Bundle.module.url(forResource: "items", withExtension: "json"))
let response = try GraphQLResult.mockedJSONResponse(
for: TestQuery(),
jsonURL: url)
let data = try XCTUnwrap(response.data)
XCTAssertEqual(data.items.edges.first?.node.__typename, "Item")
XCTAssertEqual(data.items.edges.first?.node.id, "1")
XCTAssertEqual(data.items.edges.first?.node.name, "Brad")
}