-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathgraphqlWsLink.ts
More file actions
208 lines (180 loc) · 6.2 KB
/
Copy pathgraphqlWsLink.ts
File metadata and controls
208 lines (180 loc) · 6.2 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
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
import type { ExecutionResult } from "graphql";
import { GraphQLError } from "graphql";
import { gql } from "graphql-tag";
import type { Client } from "graphql-ws";
import type { Observable } from "rxjs";
import { CombinedGraphQLErrors } from "@apollo/client/errors";
import { GraphQLWsLink } from "@apollo/client/link/subscriptions";
import {
executeWithDefaultContext as execute,
ObservableStream,
} from "@apollo/client/testing/internal";
const query = gql`
query SampleQuery {
stub {
id
}
}
`;
const mutation = gql`
mutation SampleMutation {
stub {
id
}
}
`;
const subscription = gql`
subscription SampleSubscription {
stub {
id
}
}
`;
function mockClient(subscribe: Client["subscribe"]): Client {
return {
subscribe,
// GraphQLWsLink doesn't use these methods
iterate: () => (async function* iterator() {})(),
on: () => () => {},
dispose: () => {},
terminate: () => {},
};
}
async function observableToArray<T>(o: Observable<T>): Promise<T[]> {
const out: T[] = [];
await o.forEach((v) => out.push(v));
return out;
}
describe("GraphQLWSlink", () => {
it("constructs", () => {
const client = mockClient(() => () => {});
expect(() => new GraphQLWsLink(client)).not.toThrow();
});
// TODO some sort of dependency injection
// it('should pass the correct initialization parameters to the Subscription Client', () => {
// });
it("should call subscribe on the client for a query", async () => {
const result = { data: { data: "result" } } as ExecutionResult<any, any>;
const subscribe: Client["subscribe"] = (_, sink) => {
sink.next(result);
sink.complete();
return () => {};
};
const client = mockClient(subscribe);
const link = new GraphQLWsLink(client);
const obs = execute(link, { query });
await expect(observableToArray(obs)).resolves.toEqual([result]);
});
it("should call subscribe on the client for a mutation", async () => {
const result = { data: { data: "result" } } as ExecutionResult<any, any>;
const subscribe: Client["subscribe"] = (_, sink) => {
sink.next(result);
sink.complete();
return () => {};
};
const client = mockClient(subscribe);
const link = new GraphQLWsLink(client);
const obs = execute(link, { query: mutation });
await expect(observableToArray(obs)).resolves.toEqual([result]);
});
it("should call next with multiple results for subscription", async () => {
const results = [
{ data: { data: "result1" } },
{ data: { data: "result2" } },
] as ExecutionResult<any, any>[];
const subscribe: Client["subscribe"] = (_, sink) => {
const copy = [...results];
for (const r of copy) {
sink.next(r);
}
sink.complete();
return () => {};
};
const client = mockClient(subscribe);
const link = new GraphQLWsLink(client);
const obs = execute(link, { query: subscription });
await expect(observableToArray(obs)).resolves.toEqual(results);
});
describe("should reject", () => {
it("with Error on subscription error via Error", async () => {
const subscribe: Client["subscribe"] = (_, sink) => {
sink.error(new Error("an error occurred"));
return () => {};
};
const client = mockClient(subscribe);
const link = new GraphQLWsLink(client);
const obs = execute(link, { query: subscription });
await expect(observableToArray(obs)).rejects.toEqual(
new Error("an error occurred")
);
});
it("with Error on subscription error via CloseEvent", async () => {
const subscribe: Client["subscribe"] = (_, sink) => {
// A WebSocket close event receives a CloseEvent
// See: https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close_event
sink.error(
new CloseEvent("an error occurred", {
code: 1006,
reason: "abnormally closed",
})
);
return () => {};
};
const client = mockClient(subscribe);
const link = new GraphQLWsLink(client);
const obs = execute(link, { query: subscription });
await expect(observableToArray(obs)).rejects.toEqual(
new Error("Socket closed with event 1006 abnormally closed")
);
});
it("with Error on subscription error via Event (network disconnected)", async () => {
const subscribe: Client["subscribe"] = (_, sink) => {
// A WebSocket error event receives a generic Event
// See: https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/error_event
sink.error({ target: { readyState: WebSocket.CLOSED } });
return () => {};
};
const client = mockClient(subscribe);
const link = new GraphQLWsLink(client);
const obs = execute(link, { query: subscription });
await expect(observableToArray(obs)).rejects.toEqual(
new Error("Socket closed")
);
});
it("with CombinedGraphQLErrors on subscription error via GraphQLError[]", async () => {
const subscribe: Client["subscribe"] = (_, sink) => {
sink.error([new GraphQLError("Foo bar.")]);
return () => {};
};
const client = mockClient(subscribe);
const link = new GraphQLWsLink(client);
const obs = execute(link, { query: subscription });
await expect(observableToArray(obs)).rejects.toEqual(
new CombinedGraphQLErrors({ errors: [{ message: "Foo bar." }] })
);
});
});
});
// https://github.com/apollographql/apollo-client/issues/12946
test("sends only known keys to the GraphQLWsLink", async () => {
const knownKeys = [
"query",
"variables",
"operationName",
"extensions",
].sort();
type SubscribeFn = Client["subscribe"];
const subscribe = jest.fn<ReturnType<SubscribeFn>, Parameters<SubscribeFn>>(
(_payload, sink) => {
sink.complete();
return () => {};
}
);
const client = mockClient(subscribe);
const link = new GraphQLWsLink(client);
const stream = new ObservableStream(execute(link, { query: subscription }));
await stream.takeComplete();
expect(subscribe).toHaveBeenCalledTimes(1);
const payload = subscribe.mock.calls[0][0];
expect(Object.keys(payload).sort()).toStrictEqual(knownKeys);
});