This repository has been archived by the owner on Apr 13, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 786
/
Copy pathtest-utils.tsx
234 lines (195 loc) · 6.75 KB
/
test-utils.tsx
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
import * as React from 'react';
import ApolloClient from 'apollo-client';
import {
NetworkInterface,
Request,
SubscriptionNetworkInterface,
} from 'apollo-client/transport/networkInterface';
import {
ExecutionResult,
DocumentNode,
} from 'graphql';
import { print } from 'graphql-tag/printer';
import ApolloProvider from './ApolloProvider';
export class MockedProvider extends React.Component<any, any> {
private client: any;
constructor(props, context) {
super(props, context);
const networkInterface = mockNetworkInterface.apply(null, this.props.mocks);
this.client = new ApolloClient({ networkInterface });
}
render() {
return (
<ApolloProvider client={this.client}>
{this.props.children}
</ApolloProvider>
);
}
}
export class MockedSubscriptionProvider extends React.Component<any, any> {
private client: any;
constructor(props, context) {
super(props, context);
const networkInterface = mockSubscriptionNetworkInterface(
this.props.subscriptions, ...this.props.responses
);
this.client = new ApolloClient({ networkInterface });
}
render() {
return (
<ApolloProvider client={this.client}>
{this.props.children}
</ApolloProvider>
);
}
}
// Pass in multiple mocked responses, so that you can test flows that end up
// making multiple queries to the server
export function mockNetworkInterface(
...mockedResponses: MockedResponse[]
): NetworkInterface {
return new MockNetworkInterface(...mockedResponses);
}
export function mockSubscriptionNetworkInterface(
mockedSubscriptions: MockedSubscription[], ...mockedResponses: MockedResponse[]
): MockSubscriptionNetworkInterface {
return new MockSubscriptionNetworkInterface(mockedSubscriptions, ...mockedResponses);
}
export interface ParsedRequest {
variables?: Object;
query?: DocumentNode;
debugName?: string;
}
export interface MockedResponse {
request: ParsedRequest;
result?: ExecutionResult;
error?: Error;
delay?: number;
newData?: () => any;
}
export interface MockedSubscriptionResult {
result?: ExecutionResult;
error?: Error;
delay?: number;
}
export interface MockedSubscription {
request: ParsedRequest;
results?: MockedSubscriptionResult[];
id?: number;
}
export class MockNetworkInterface implements NetworkInterface {
private mockedResponsesByKey: { [key: string]: MockedResponse[] } = {};
constructor(...mockedResponses: MockedResponse[]) {
mockedResponses.forEach((mockedResponse) => {
this.addMockedReponse(mockedResponse);
});
}
public addMockedReponse(mockedResponse: MockedResponse) {
const key = requestToKey(mockedResponse.request);
let mockedResponses = this.mockedResponsesByKey[key];
if (!mockedResponses) {
mockedResponses = [];
this.mockedResponsesByKey[key] = mockedResponses;
}
mockedResponses.push(mockedResponse);
}
public query(request: Request) {
return new Promise((resolve, reject) => {
const parsedRequest: ParsedRequest = {
query: request.query,
variables: request.variables,
debugName: request.debugName,
};
const key = requestToKey(parsedRequest);
if (!this.mockedResponsesByKey[key]) {
throw new Error('No more mocked responses for the query: ' + print(request.query));
}
const original = [...this.mockedResponsesByKey[key]];
const { result, error, delay, newData } = this.mockedResponsesByKey[key].shift() || {} as any;
if (newData) {
original[0].result = newData();
this.mockedResponsesByKey[key].push(original[0]);
}
if (!result && !error) {
throw new Error(`Mocked response should contain either result or error: ${key}`);
}
setTimeout(() => {
if (error) return reject(error);
return resolve(result);
}, delay ? delay : 1);
});
}
}
export class MockSubscriptionNetworkInterface extends MockNetworkInterface implements SubscriptionNetworkInterface {
public mockedSubscriptionsByKey: { [key: string ]: MockedSubscription[] } = {};
public mockedSubscriptionsById: { [id: number]: MockedSubscription} = {};
public handlersById: {[id: number]: (error: any, result: any) => void} = {};
public subId: number;
constructor(mockedSubscriptions: MockedSubscription[], ...mockedResponses: MockedResponse[]) {
super(...mockedResponses);
this.subId = 0;
mockedSubscriptions.forEach((sub) => {
this.addMockedSubscription(sub);
});
}
public generateSubscriptionId() {
const requestId = this.subId;
this.subId++;
return requestId;
}
public addMockedSubscription(mockedSubscription: MockedSubscription) {
const key = requestToKey(mockedSubscription.request);
if (mockedSubscription.id === undefined) {
mockedSubscription.id = this.generateSubscriptionId();
}
let mockedSubs = this.mockedSubscriptionsByKey[key];
if (!mockedSubs) {
mockedSubs = [];
this.mockedSubscriptionsByKey[key] = mockedSubs;
}
mockedSubs.push(mockedSubscription);
}
public subscribe(request: Request, handler: (error: any, result: any) => void): number {
const parsedRequest: ParsedRequest = {
query: request.query,
variables: request.variables,
debugName: request.debugName,
};
const key = requestToKey(parsedRequest);
if (this.mockedSubscriptionsByKey.hasOwnProperty(key)) {
const subscription = this.mockedSubscriptionsByKey[key].shift();
this.handlersById[subscription.id] = handler;
this.mockedSubscriptionsById[subscription.id] = subscription;
return subscription.id;
} else {
throw new Error('Network interface does not have subscription associated with this request.');
}
};
public fireResult(id: number) {
const handler = this.handlersById[id];
if (this.mockedSubscriptionsById.hasOwnProperty(id.toString())) {
const subscription = this.mockedSubscriptionsById[id];
if (subscription.results.length === 0) {
throw new Error(`No more mocked subscription responses for the query: ` +
`${print(subscription.request.query)}, variables: ${JSON.stringify(subscription.request.variables)}`);
}
const response = subscription.results.shift();
setTimeout(() => {
handler(response.error, response.result);
}, response.delay ? response.delay : 0);
} else {
throw new Error('Network interface does not have subscription associated with this id.');
}
}
public unsubscribe(id: number) {
delete this.mockedSubscriptionsById[id];
}
}
function requestToKey(request: ParsedRequest): string {
const queryString = request.query && print(request.query);
return JSON.stringify({
variables: request.variables,
debugName: request.debugName,
query: queryString,
});
}