forked from apollographql/apollo-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMockedProvider.tsx
More file actions
84 lines (75 loc) · 2.26 KB
/
Copy pathMockedProvider.tsx
File metadata and controls
84 lines (75 loc) · 2.26 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import * as React from "react";
import { ApolloClient } from "@apollo/client";
import type { ApolloCache } from "@apollo/client/cache";
import { InMemoryCache as Cache } from "@apollo/client/cache";
import type { ApolloLink } from "@apollo/client/link";
import type { LocalState } from "@apollo/client/local-state";
import { ApolloProvider } from "@apollo/client/react";
import { MockLink } from "@apollo/client/testing";
export interface MockedProviderProps {
mocks?: ReadonlyArray<MockLink.MockedResponse<any, any>>;
defaultOptions?: ApolloClient.DefaultOptions;
cache?: ApolloCache;
localState?: LocalState;
childProps?: object;
children?: any;
link?: ApolloLink;
showWarnings?: boolean;
mockLinkDefaultOptions?: MockLink.DefaultOptions;
/**
* Configuration used by the [Apollo Client Devtools extension](https://www.apollographql.com/docs/react/development-testing/developer-tooling/#apollo-client-devtools) for this client.
*
* @since 3.14.0
*/
devtools?: ApolloClient.Options["devtools"];
}
interface MockedProviderState {
client: ApolloClient;
}
export class MockedProvider extends React.Component<
MockedProviderProps,
MockedProviderState
> {
constructor(props: MockedProviderProps) {
super(props);
const {
mocks,
defaultOptions,
cache,
localState,
link,
showWarnings,
mockLinkDefaultOptions,
devtools,
} = this.props;
const client = new ApolloClient({
cache: cache || new Cache(),
defaultOptions,
link:
link ||
new MockLink(mocks || [], {
showWarnings,
defaultOptions: mockLinkDefaultOptions,
}),
localState,
devtools: devtools ?? { enabled: false },
});
this.state = {
client,
};
}
public render() {
const { children, childProps } = this.props;
const { client } = this.state;
return React.isValidElement(children) ?
<ApolloProvider client={client}>
{React.cloneElement(React.Children.only(children), { ...childProps })}
</ApolloProvider>
: null;
}
public componentWillUnmount() {
// Since this.state.client was created in the constructor, it's this
// MockedProvider's responsibility to terminate it.
this.state.client.stop();
}
}