我正在使用两个GraphQL API,一个用于数据,另一个用于内容。因此,使用以下代码基于https://www.jamalx31.com/tech-posts/using-apollo-with-multiple-graphql-endpoints
启用此功能import { HttpLink, InMemoryCache } from 'apollo-boost';
import { ApolloLink } from 'apollo-link';
import { ApolloClient } from 'apollo-client';
import getConfig from 'next/config';
import fetch from 'isomorphic-unfetch';
import { IncomingHttpHeaders } from 'http';
let apolloClientInstance: ApolloClient<unknown> | null = null;
const { publicRuntimeConfig } = getConfig();
const createApolloClient = (
initialState = {},
headers?: IncomingHttpHeaders
) => {
const gqlAPI1 = new HttpLink({
uri: publicRuntimeConfig.GRAPHQL_API,
credentials: 'include',
fetch,
headers: { 'key': '1234' }
});
const gqlAPI2 = new HttpLink({
uri: API2_URL,
fetch,
headers: {
authorization: `Bearer ${TOKEN}`,
'Content-Language': 'en-us'
}
});
return new ApolloClient({
link: ApolloLink.split(
(operation) => operation.getContext().clientName === 'cms',
gqlAPI2,
gqlAPI1
),
cache: new InMemoryCache().restore(initialState)
});
};
我正尝试为此编写单元测试,如下所述。
/**
* @jest-environment node
*/
import React from 'react';
jest.mock('next-with-apollo');
jest.mock('apollo-boost');
jest.mock('@apollo/react-hooks');
jest.mock('isomorphic-unfetch');
import ApolloClient, {
ApolloLink,
HttpLink,
InMemoryCache
} from 'apollo-boost';
import nextWithApollo from 'next-with-apollo';
import fetch from 'isomorphic-unfetch';
const mockInMemoryCache = {
restore: jest.fn().mockReturnValue('mockInMemoryCache')
};
(InMemoryCache as jest.Mock).mockReturnValue(mockInMemoryCache);
jest.requireActual('../../shared/graphql/withApollo');
describe('client', () => {
const client = (nextWithApollo as jest.Mock).mock.calls[0][0];
it('is configured just the way we want it', () => {
const gqlAPI1 = new HttpLink({
uri: 'https://xxxxxxxxxxxx.com/graphql',
credentials: 'include',
fetch,
headers: { 'key': '1234' }
});
const gqlAPI2 = new HttpLink({
uri: 'https://xxxxxxxxxxx.com/',
fetch,
headers: {
authorization: `Bearer sadsdasdasdsadsa`,
'Content-Language': 'en-us'
}
});
const link = ApolloLink.split(
(operation) => operation.getContext().clientName === 'cms',
gqlAPI2,
gqlAPI1
);
expect(ApolloClient).not.toBeCalled();
client({});
expect(ApolloClient).toBeCalledWith({
link: link,
cache: 'mockInMemoryCache'
});
});
});
我遇到错误了
● Apollo provider › client › is configured just the way we want it
expect(jest.fn()).toBeCalledWith(...expected)
Expected: {"cache": "mockInMemoryCache", "link": undefined}
Number of calls: 0
67 | expect(ApolloClient).not.toBeCalled();
68 | client({});
> 69 | expect(ApolloClient).toBeCalledWith({
| ^
70 | link: link,
71 | cache: 'mockInMemoryCache'
72 | })
我无法找到问题所在,可以看到"link": undefined
,但又不确定为什么会这样。提前非常感谢