/
ApolloServerBase.test.ts
304 lines (268 loc) 路 8.17 KB
/
ApolloServerBase.test.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
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
import { ApolloServerBase } from '../ApolloServer';
import { buildServiceDefinition } from '@apollographql/apollo-tools';
import { gql } from '../';
import { Logger } from 'apollo-server-types';
import { ApolloServerPlugin } from 'apollo-server-plugin-base';
import type { GraphQLSchema } from 'graphql';
const typeDefs = gql`
type Query {
hello: String
error: Boolean
contextFoo: String
}
`;
const resolvers = {
Query: {
hello() {
return 'world';
},
error() {
throw new Error('A test error');
},
contextFoo(_root: any, _args: any, context: any) {
return context.foo;
},
},
};
describe('ApolloServerBase construction', () => {
it('succeeds when a valid configuration options are provided to typeDefs and resolvers', () => {
expect(() => new ApolloServerBase({ typeDefs, resolvers })).not.toThrow();
});
it('succeeds when a valid GraphQLSchema is provided to the schema configuration option', () => {
expect(
() =>
new ApolloServerBase({
schema: buildServiceDefinition([{ typeDefs, resolvers }]).schema,
}),
).not.toThrow();
});
it('succeeds when passed a graphVariant in construction', () => {
expect(() =>
new ApolloServerBase({
typeDefs,
resolvers,
engine: {
graphVariant: 'foo',
apiKey: 'not:real:key',
},
}).stop(),
).not.toThrow();
});
it('spits out a deprecation warning when passed a schemaTag in construction', () => {
const spyConsoleWarn = jest.spyOn(console, 'warn').mockImplementation();
expect(() =>
new ApolloServerBase({
typeDefs,
resolvers,
engine: {
schemaTag: 'foo',
apiKey: 'not:real:key',
},
}).stop(),
).not.toThrow();
expect(spyConsoleWarn).toBeCalledWith(
expect.stringMatching(/schemaTag.*graphVariant/),
);
spyConsoleWarn.mockRestore();
});
it('throws when passed a schemaTag and graphVariant in construction', () => {
expect(
() =>
new ApolloServerBase({
schema: buildServiceDefinition([{ typeDefs, resolvers }]).schema,
engine: {
schemaTag: 'foo',
graphVariant: 'heck',
apiKey: 'not:real:key',
},
}),
).toThrow();
});
it('throws when a GraphQLSchema is not provided to the schema configuration option', () => {
expect(() => {
new ApolloServerBase({
schema: {} as GraphQLSchema,
});
}).toThrowErrorMatchingInlineSnapshot(
`"Expected {} to be a GraphQL schema."`,
);
});
it('throws when the no schema configuration option is provided', () => {
expect(() => {
new ApolloServerBase({});
}).toThrowErrorMatchingInlineSnapshot(
`"Apollo Server requires either an existing schema, modules or typeDefs"`,
);
});
});
describe('ApolloServerBase start', () => {
const failToStartPlugin: ApolloServerPlugin = {
async serverWillStart() {
throw Error('nope');
},
};
const redactedMessage =
'This data graph is missing a valid configuration. More details may be available in the server logs.';
it('start throws on startup error', async () => {
const server = new ApolloServerBase({
typeDefs,
resolvers,
plugins: [failToStartPlugin],
});
await expect(server.start()).rejects.toThrow('nope');
});
it('execute throws redacted message on implicit startup error', async () => {
const error = jest.fn();
const logger: Logger = {
debug: jest.fn(),
info: jest.fn(),
warn: jest.fn(),
error,
};
const server = new ApolloServerBase({
typeDefs,
resolvers,
plugins: [failToStartPlugin],
logger,
});
// Run the operation twice (the first will kick off the start process). We
// want to see the same error thrown and log message for the "kick it off"
// call as the subsequent call.
await expect(
server.executeOperation({ query: '{__typename}' }),
).rejects.toThrow(redactedMessage);
await expect(
server.executeOperation({ query: '{__typename}' }),
).rejects.toThrow(redactedMessage);
expect(error).toHaveBeenCalledTimes(2);
expect(error.mock.calls[0][0]).toMatch(
/Apollo Server was started implicitly.*nope/,
);
expect(error.mock.calls[1][0]).toMatch(
/Apollo Server was started implicitly.*nope/,
);
});
});
describe('ApolloServerBase executeOperation', () => {
it('returns error information without details by default', async () => {
const server = new ApolloServerBase({
typeDefs,
resolvers,
});
const result = await server.executeOperation({ query: 'query { error }' });
expect(result.errors).toHaveLength(1);
expect(result.errors?.[0].extensions).toStrictEqual({
code: 'INTERNAL_SERVER_ERROR',
});
});
it('returns error information with details when debug is enabled', async () => {
const server = new ApolloServerBase({
typeDefs,
resolvers,
debug: true,
});
const result = await server.executeOperation({ query: 'query { error }' });
expect(result.errors).toHaveLength(1);
expect(result.errors?.[0].extensions?.code).toBe('INTERNAL_SERVER_ERROR');
expect(result.errors?.[0].extensions?.exception?.stacktrace).toBeDefined();
});
it('works with string', async () => {
const server = new ApolloServerBase({
typeDefs,
resolvers,
});
const result = await server.executeOperation({ query: '{ hello }' });
expect(result.errors).toBeUndefined();
expect(result.data?.hello).toBe('world');
});
it('works with AST', async () => {
const server = new ApolloServerBase({
typeDefs,
resolvers,
});
const result = await server.executeOperation({
query: gql`
{
hello
}
`,
});
expect(result.errors).toBeUndefined();
expect(result.data?.hello).toBe('world');
});
it('parse errors', async () => {
const server = new ApolloServerBase({
typeDefs,
resolvers,
});
const result = await server.executeOperation({ query: '{' });
expect(result.errors).toHaveLength(1);
expect(result.errors?.[0].extensions?.code).toBe('GRAPHQL_PARSE_FAILED');
});
it('passes its second argument to context function', async () => {
const server = new ApolloServerBase({
typeDefs,
resolvers,
context: ({ fooIn }) => ({ foo: fooIn }),
});
const result = await server.executeOperation(
{ query: '{ contextFoo }' },
{ fooIn: 'bla' },
);
expect(result.errors).toBeUndefined();
expect(result.data?.contextFoo).toBe('bla');
});
});
describe('environment variables', () => {
const OLD_ENV = process.env;
beforeEach(() => {
jest.resetModules();
process.env = { ...OLD_ENV };
delete process.env.ENGINE_API_KEY;
delete process.env.APOLLO_KEY;
});
afterEach(() => {
process.env = OLD_ENV;
});
it('constructs a reporting agent with the ENGINE_API_KEY (deprecated) environment variable and warns', async () => {
// set the variables
process.env.ENGINE_API_KEY = 'just:fake:stuff';
const warn = jest.fn();
const mockLogger: Logger = {
debug: jest.fn(),
info: jest.fn(),
warn,
error: jest.fn(),
};
const server = new ApolloServerBase({
typeDefs,
resolvers,
apollo: { graphVariant: 'xxx' },
logger: mockLogger,
});
await server.stop();
expect(warn).toHaveBeenCalledTimes(1);
expect(warn.mock.calls[0][0]).toMatch(/deprecated.*ENGINE_API_KEY/);
});
it('warns with both the legacy env var and new env var set', async () => {
// set the variables
process.env.ENGINE_API_KEY = 'just:fake:stuff';
process.env.APOLLO_KEY = 'also:fake:stuff';
const warn = jest.fn();
const mockLogger: Logger = {
debug: jest.fn(),
info: jest.fn(),
warn,
error: jest.fn(),
};
const server = new ApolloServerBase({
typeDefs,
resolvers,
apollo: { graphVariant: 'xxx' },
logger: mockLogger,
});
await server.stop();
expect(warn).toHaveBeenCalledTimes(1);
expect(warn.mock.calls[0][0]).toMatch(/Using.*APOLLO_KEY.*ENGINE_API_KEY/);
});
});