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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
|
'use strict'
const { test } = require('tap')
const { createServer } = require('http')
const { promisify } = require('util')
const { MockAgent, MockPool, getGlobalDispatcher, setGlobalDispatcher, request } = require('..')
const { kUrl } = require('../lib/core/symbols')
const { nodeMajor } = require('../lib/core/util')
const { kDispatches } = require('../lib/mock/mock-symbols')
const { InvalidArgumentError } = require('../lib/core/errors')
const { MockInterceptor } = require('../lib/mock/mock-interceptor')
const { getResponse } = require('../lib/mock/mock-utils')
const Dispatcher = require('../lib/dispatcher')
test('MockPool - constructor', t => {
t.plan(3)
t.test('fails if opts.agent does not implement `get` method', t => {
t.plan(1)
t.throws(() => new MockPool('http://localhost:9999', { agent: { get: 'not a function' } }), InvalidArgumentError)
})
t.test('sets agent', t => {
t.plan(1)
t.doesNotThrow(() => new MockPool('http://localhost:9999', { agent: new MockAgent() }))
})
t.test('should implement the Dispatcher API', t => {
t.plan(1)
const mockPool = new MockPool('http://localhost:9999', { agent: new MockAgent() })
t.type(mockPool, Dispatcher)
})
})
test('MockPool - dispatch', t => {
t.plan(2)
t.test('should handle a single interceptor', (t) => {
t.plan(1)
const baseUrl = 'http://localhost:9999'
const mockAgent = new MockAgent()
t.teardown(mockAgent.close.bind(mockAgent))
const mockPool = mockAgent.get(baseUrl)
this[kUrl] = new URL('http://localhost:9999')
mockPool[kDispatches] = [
{
path: '/foo',
method: 'GET',
data: {
statusCode: 200,
data: 'hello',
headers: {},
trailers: {},
error: null
}
}
]
t.doesNotThrow(() => mockPool.dispatch({
path: '/foo',
method: 'GET'
}, {
onHeaders: (_statusCode, _headers, resume) => resume(),
onData: () => {},
onComplete: () => {}
}))
})
t.test('should directly throw error from mockDispatch function if error is not a MockNotMatchedError', (t) => {
t.plan(1)
const baseUrl = 'http://localhost:9999'
const mockAgent = new MockAgent()
t.teardown(mockAgent.close.bind(mockAgent))
const mockPool = mockAgent.get(baseUrl)
this[kUrl] = new URL('http://localhost:9999')
mockPool[kDispatches] = [
{
path: '/foo',
method: 'GET',
data: {
statusCode: 200,
data: 'hello',
headers: {},
trailers: {},
error: null
}
}
]
t.throws(() => mockPool.dispatch({
path: '/foo',
method: 'GET'
}, {
onHeaders: (_statusCode, _headers, resume) => { throw new Error('kaboom') },
onData: () => {},
onComplete: () => {}
}), new Error('kaboom'))
})
})
test('MockPool - intercept should return a MockInterceptor', (t) => {
t.plan(1)
const baseUrl = 'http://localhost:9999'
const mockAgent = new MockAgent()
t.teardown(mockAgent.close.bind(mockAgent))
const mockPool = mockAgent.get(baseUrl)
const interceptor = mockPool.intercept({
path: '/foo',
method: 'GET'
})
t.ok(interceptor instanceof MockInterceptor)
})
test('MockPool - intercept validation', (t) => {
t.plan(3)
t.test('it should error if no options specified in the intercept', t => {
t.plan(1)
const mockAgent = new MockAgent()
t.teardown(mockAgent.close.bind(mockAgent))
const mockPool = mockAgent.get('http://localhost:9999')
t.throws(() => mockPool.intercept(), new InvalidArgumentError('opts must be an object'))
})
t.test('it should error if no path specified in the intercept', t => {
t.plan(1)
const mockAgent = new MockAgent()
t.teardown(mockAgent.close.bind(mockAgent))
const mockPool = mockAgent.get('http://localhost:9999')
t.throws(() => mockPool.intercept({}), new InvalidArgumentError('opts.path must be defined'))
})
t.test('it should default to GET if no method specified in the intercept', t => {
t.plan(1)
const mockAgent = new MockAgent()
t.teardown(mockAgent.close.bind(mockAgent))
const mockPool = mockAgent.get('http://localhost:9999')
t.doesNotThrow(() => mockPool.intercept({ path: '/foo' }))
})
})
test('MockPool - close should run without error', async (t) => {
t.plan(1)
const baseUrl = 'http://localhost:9999'
const mockAgent = new MockAgent()
t.teardown(mockAgent.close.bind(mockAgent))
const mockPool = mockAgent.get(baseUrl)
mockPool[kDispatches] = [
{
path: '/foo',
method: 'GET',
data: {
statusCode: 200,
data: 'hello',
headers: {},
trailers: {},
error: null
}
}
]
await t.resolves(mockPool.close())
})
test('MockPool - should be able to set as globalDispatcher', async (t) => {
t.plan(3)
const server = createServer((req, res) => {
res.setHeader('content-type', 'text/plain')
res.end('should not be called')
t.fail('should not be called')
t.end()
})
t.teardown(server.close.bind(server))
await promisify(server.listen.bind(server))(0)
const baseUrl = `http://localhost:${server.address().port}`
const mockAgent = new MockAgent()
t.teardown(mockAgent.close.bind(mockAgent))
const mockPool = mockAgent.get(baseUrl)
t.type(mockPool, MockPool)
setGlobalDispatcher(mockPool)
mockPool.intercept({
path: '/foo',
method: 'GET'
}).reply(200, 'hello')
const { statusCode, body } = await request(`${baseUrl}/foo`, {
method: 'GET'
})
t.equal(statusCode, 200)
const response = await getResponse(body)
t.same(response, 'hello')
})
test('MockPool - should be able to use as a local dispatcher', async (t) => {
t.plan(3)
const server = createServer((req, res) => {
res.setHeader('content-type', 'text/plain')
res.end('should not be called')
t.fail('should not be called')
t.end()
})
t.teardown(server.close.bind(server))
await promisify(server.listen.bind(server))(0)
const baseUrl = `http://localhost:${server.address().port}`
const mockAgent = new MockAgent()
t.teardown(mockAgent.close.bind(mockAgent))
const mockPool = mockAgent.get(baseUrl)
t.type(mockPool, MockPool)
mockPool.intercept({
path: '/foo',
method: 'GET'
}).reply(200, 'hello')
const { statusCode, body } = await request(`${baseUrl}/foo`, {
method: 'GET',
dispatcher: mockPool
})
t.equal(statusCode, 200)
const response = await getResponse(body)
t.same(response, 'hello')
})
test('MockPool - basic intercept with MockPool.request', async (t) => {
t.plan(5)
const server = createServer((req, res) => {
res.setHeader('content-type', 'text/plain')
res.end('should not be called')
t.fail('should not be called')
t.end()
})
t.teardown(server.close.bind(server))
await promisify(server.listen.bind(server))(0)
const baseUrl = `http://localhost:${server.address().port}`
const mockAgent = new MockAgent()
t.teardown(mockAgent.close.bind(mockAgent))
const mockPool = mockAgent.get(baseUrl)
t.type(mockPool, MockPool)
mockPool.intercept({
path: '/foo?hello=there&see=ya',
method: 'POST',
body: 'form1=data1&form2=data2'
}).reply(200, { foo: 'bar' }, {
headers: { 'content-type': 'application/json' },
trailers: { 'Content-MD5': 'test' }
})
const { statusCode, headers, trailers, body } = await mockPool.request({
origin: baseUrl,
path: '/foo?hello=there&see=ya',
method: 'POST',
body: 'form1=data1&form2=data2'
})
t.equal(statusCode, 200)
t.equal(headers['content-type'], 'application/json')
t.same(trailers, { 'content-md5': 'test' })
const jsonResponse = JSON.parse(await getResponse(body))
t.same(jsonResponse, {
foo: 'bar'
})
})
// https://github.com/nodejs/undici/issues/1546
test('MockPool - correct errors when consuming invalid JSON body', async (t) => {
const oldDispatcher = getGlobalDispatcher()
const mockAgent = new MockAgent()
mockAgent.disableNetConnect()
setGlobalDispatcher(mockAgent)
t.teardown(() => setGlobalDispatcher(oldDispatcher))
const mockPool = mockAgent.get('https://google.com')
mockPool.intercept({
path: 'https://google.com'
}).reply(200, 'it\'s just a text')
const { body } = await request('https://google.com')
await t.rejects(body.json(), SyntaxError)
t.end()
})
test('MockPool - allows matching headers in fetch', { skip: nodeMajor < 16 }, async (t) => {
const { fetch } = require('../index')
const oldDispatcher = getGlobalDispatcher()
const baseUrl = 'http://localhost:9999'
const mockAgent = new MockAgent()
mockAgent.disableNetConnect()
setGlobalDispatcher(mockAgent)
t.teardown(async () => {
await mockAgent.close()
setGlobalDispatcher(oldDispatcher)
})
const pool = mockAgent.get(baseUrl)
pool.intercept({
path: '/foo',
method: 'GET',
headers: {
accept: 'application/json'
}
}).reply(200, { ok: 1 }).times(3)
await t.resolves(
fetch(`${baseUrl}/foo`, {
headers: {
accept: 'application/json'
}
})
)
// no 'accept: application/json' header sent, not matched
await t.rejects(fetch(`${baseUrl}/foo`))
// not 'accept: application/json', not matched
await t.rejects(fetch(`${baseUrl}/foo`), {
headers: {
accept: 'text/plain'
}
}, TypeError)
t.end()
})
|