javascript graphql和apollo客户端测试的工作示例
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript graphql和apollo客户端测试的工作示例相关的知识,希望对你有一定的参考价值。
import 'mocha';
import {expect} from 'chai';
import 'isomorphic-fetch';
import ApolloClient from 'apollo-client';
import gql from 'graphql-tag';
import {print} from 'graphql-tag/bundledPrinter';
describe('some test', () => {
it('should pass', () => {
const query = gql`
query people {
allPeople(first: 1) {
people {
name
}
}
}
`;
const result = {
data: {
allPeople: {
people: [
{
name: 'Luke Skywalker',
},
],
},
},
};
const networkInterface = new MockNetworkInterface({
request: {query},
result
});
const client = new ApolloClient({
networkInterface,
addTypename: false
});
return client.query({query})
.then(d => {
return expect(d.data).to.eql(result.data);
});
});
});
class MockNetworkInterface {
mockedResponsesByKey = [];
constructor(mockedResponse) {
this.addMockedResponse(mockedResponse);
}
addMockedResponse(mockedResponse) {
const key = requestToKey(mockedResponse.request);
let mockedResponses = this.mockedResponsesByKey[key];
if (!mockedResponses) {
mockedResponses = [];
this.mockedResponsesByKey[key] = mockedResponses;
}
mockedResponses.push(mockedResponse);
}
query(request) {
return new Promise((resolve, reject) => {
const parsedRequest = {
query: request.query,
variables: request.variables,
debugName: request.debugName,
};
const key = requestToKey(parsedRequest);
const responses = this.mockedResponsesByKey[key];
if (!responses || responses.length === 0) {
throw new Error(`No more mocked responses for the query: ${print(request.query)}, variables: ${JSON.stringify(request.variables)}`);
}
const {result, error, delay} = responses.shift();
if (!result && !error) {
throw new Error(`Mocked response should contain either result or error: ${key}`);
}
setTimeout(() => {
if (error) {
reject(error);
} else {
resolve(result);
}
}, delay ? delay : 0);
});
}
}
function requestToKey(request) {
const queryString = request.query && print(request.query);
return JSON.stringify({
variables: request.variables || {},
debugName: request.debugName,
query: queryString,
});
}
以上是关于javascript graphql和apollo客户端测试的工作示例的主要内容,如果未能解决你的问题,请参考以下文章
javascript 使用Apollo Graphql的Vue组件
javascript GraphQL Apollo Chrome控制台查询
ReactJS/Javascript/Graphql/React-apollo:无法读取未定义的属性“正在加载”
使用 Express-GraphQL 和 React-Apollo 订阅 GraphQL
在 GraphQL 和 Apollo 中检索数组
GraphQL - “Federations”是普通 Graphql 的事情还是 Apollo 的事情?