forked from Mike-Gibson/mock-apollo-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmockClient.ts
44 lines (34 loc) · 1.37 KB
/
mockClient.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import { ApolloClientOptions, ApolloClient, DocumentNode } from '@apollo/client/core';
import { InMemoryCache as Cache, NormalizedCacheObject } from '@apollo/client/cache';
import { MissingHandlerPolicy, MockLink } from './mockLink';
import { IMockSubscription } from './mockSubscription';
export type RequestHandler<TData = any, TVariables = any> =
(variables: TVariables) =>
| Promise<RequestHandlerResponse<TData>>
| IMockSubscription<TData>;
export type RequestHandlerResponse<T> =
| { data: T }
| { errors: any[] };
export type MockApolloClient = ApolloClient<NormalizedCacheObject> &
{ setRequestHandler: (query: DocumentNode, handler: RequestHandler) => void };
interface CustomOptions {
missingHandlerPolicy?: MissingHandlerPolicy;
}
export type MockApolloClientOptions = Partial<Omit<ApolloClientOptions<NormalizedCacheObject>, 'link'>> & CustomOptions | undefined;
export const createMockClient = (options?: MockApolloClientOptions): MockApolloClient => {
if ((options as any)?.link) {
throw new Error('Providing link to use is not supported.');
}
const mockLink = new MockLink();
const client = new ApolloClient({
cache: new Cache({
addTypename: false,
}),
...options,
link: mockLink
});
const mockMethods = {
setRequestHandler: mockLink.setRequestHandler.bind(mockLink),
};
return Object.assign(client, mockMethods);
}