@depup/supertest 7.2.2-depup.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,23 @@
1
+ (The MIT License)
2
+
3
+ Copyright (c) 2014 TJ Holowaychuk <tj@vision-media.ca> and other
4
+ contributors.
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining
7
+ a copy of this software and associated documentation files (the
8
+ 'Software'), to deal in the Software without restriction, including
9
+ without limitation the rights to use, copy, modify, merge, publish,
10
+ distribute, sublicense, and/or sell copies of the Software, and to
11
+ permit persons to whom the Software is furnished to do so, subject to
12
+ the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be
15
+ included in all copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
18
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
20
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
21
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
22
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
23
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,471 @@
1
+ # [supertest](https://forwardemail.github.io/superagent/)
2
+
3
+ [![build status](https://github.com/forwardemail/supertest/actions/workflows/ci.yml/badge.svg)](https://github.com/forwardemail/supertest/actions/workflows/ci.yml)
4
+ [![code coverage](https://img.shields.io/codecov/c/github/ladjs/supertest.svg)](https://codecov.io/gh/ladjs/supertest)
5
+ [![code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/sindresorhus/xo)
6
+ [![styled with prettier](https://img.shields.io/badge/styled_with-prettier-ff69b4.svg)](https://github.com/prettier/prettier)
7
+ [![made with lass](https://img.shields.io/badge/made_with-lass-95CC28.svg)](https://lass.js.org)
8
+ [![license](https://img.shields.io/github/license/ladjs/supertest.svg)](LICENSE)
9
+
10
+ > HTTP assertions made easy via [superagent](http://github.com/ladjs/superagent). Maintained for [Forward Email](https://github.com/forwardemail) and [Lad](https://github.com/ladjs).
11
+
12
+ ## About
13
+
14
+ The motivation with this module is to provide a high-level abstraction for testing
15
+ HTTP, while still allowing you to drop down to the [lower-level API](https://forwardemail.github.io/superagent/) provided by superagent.
16
+
17
+ ## Getting Started
18
+
19
+ Install supertest as an npm module and save it to your package.json file as a development dependency:
20
+
21
+ ```bash
22
+ npm install supertest --save-dev
23
+ ```
24
+
25
+ Once installed it can now be referenced by simply calling ```require('supertest');```
26
+
27
+ ## Example
28
+
29
+ You may pass an `http.Server`, or a `Function` to `request()` - if the server is not
30
+ already listening for connections then it is bound to an ephemeral port for you so
31
+ there is no need to keep track of ports.
32
+
33
+ supertest works with any test framework, here is an example without using any
34
+ test framework at all:
35
+
36
+ ```js
37
+ const request = require('supertest');
38
+ const express = require('express');
39
+
40
+ const app = express();
41
+
42
+ app.get('/user', function(req, res) {
43
+ res.status(200).json({ name: 'john' });
44
+ });
45
+
46
+ request(app)
47
+ .get('/user')
48
+ .expect('Content-Type', /json/)
49
+ .expect('Content-Length', '15')
50
+ .expect(200)
51
+ .end(function(err, res) {
52
+ if (err) throw err;
53
+ });
54
+ ```
55
+
56
+ To enable http2 protocol, simply append an options to `request` or `request.agent`:
57
+
58
+ ```js
59
+ const request = require('supertest');
60
+ const express = require('express');
61
+
62
+ const app = express();
63
+
64
+ app.get('/user', function(req, res) {
65
+ res.status(200).json({ name: 'john' });
66
+ });
67
+
68
+ request(app, { http2: true })
69
+ .get('/user')
70
+ .expect('Content-Type', /json/)
71
+ .expect('Content-Length', '15')
72
+ .expect(200)
73
+ .end(function(err, res) {
74
+ if (err) throw err;
75
+ });
76
+
77
+ request.agent(app, { http2: true })
78
+ .get('/user')
79
+ .expect('Content-Type', /json/)
80
+ .expect('Content-Length', '15')
81
+ .expect(200)
82
+ .end(function(err, res) {
83
+ if (err) throw err;
84
+ });
85
+ ```
86
+
87
+ Here's an example with mocha, note how you can pass `done` straight to any of the `.expect()` calls:
88
+
89
+ ```js
90
+ describe('GET /user', function() {
91
+ it('responds with json', function(done) {
92
+ request(app)
93
+ .get('/user')
94
+ .set('Accept', 'application/json')
95
+ .expect('Content-Type', /json/)
96
+ .expect(200, done);
97
+ });
98
+ });
99
+ ```
100
+
101
+ You can use `auth` method to pass HTTP username and password in the same way as in the [superagent](https://forwardemail.github.io/superagent/#authentication):
102
+
103
+ ```js
104
+ describe('GET /user', function() {
105
+ it('responds with json', function(done) {
106
+ request(app)
107
+ .get('/user')
108
+ .auth('username', 'password')
109
+ .set('Accept', 'application/json')
110
+ .expect('Content-Type', /json/)
111
+ .expect(200, done);
112
+ });
113
+ });
114
+ ```
115
+
116
+ One thing to note with the above statement is that superagent now sends any HTTP
117
+ error (anything other than a 2XX response code) to the callback as the first argument if
118
+ you do not add a status code expect (i.e. `.expect(302)`).
119
+
120
+ If you are using the `.end()` method `.expect()` assertions that fail will
121
+ not throw - they will return the assertion as an error to the `.end()` callback. In
122
+ order to fail the test case, you will need to rethrow or pass `err` to `done()`, as follows:
123
+
124
+ ```js
125
+ describe('POST /users', function() {
126
+ it('responds with json', function(done) {
127
+ request(app)
128
+ .post('/users')
129
+ .send({name: 'john'})
130
+ .set('Accept', 'application/json')
131
+ .expect('Content-Type', /json/)
132
+ .expect(200)
133
+ .end(function(err, res) {
134
+ if (err) return done(err);
135
+ return done();
136
+ });
137
+ });
138
+ });
139
+ ```
140
+
141
+ You can also use promises:
142
+
143
+ ```js
144
+ describe('GET /users', function() {
145
+ it('responds with json', function() {
146
+ return request(app)
147
+ .get('/users')
148
+ .set('Accept', 'application/json')
149
+ .expect('Content-Type', /json/)
150
+ .expect(200)
151
+ .then(response => {
152
+ expect(response.body.email).toEqual('foo@bar.com');
153
+ })
154
+ });
155
+ });
156
+ ```
157
+
158
+ Or async/await syntax:
159
+
160
+ ```js
161
+ describe('GET /users', function() {
162
+ it('responds with json', async function() {
163
+ const response = await request(app)
164
+ .get('/users')
165
+ .set('Accept', 'application/json')
166
+ expect(response.headers["content-type"]).toMatch(/json/);
167
+ expect(response.status).toEqual(200);
168
+ expect(response.body.email).toEqual('foo@bar.com');
169
+ });
170
+ });
171
+ ```
172
+
173
+ Expectations are run in the order of definition. This characteristic can be used
174
+ to modify the response body or headers before executing an assertion.
175
+
176
+ ```js
177
+ describe('POST /user', function() {
178
+ it('user.name should be an case-insensitive match for "john"', function(done) {
179
+ request(app)
180
+ .post('/user')
181
+ .send('name=john') // x-www-form-urlencoded upload
182
+ .set('Accept', 'application/json')
183
+ .expect(function(res) {
184
+ res.body.id = 'some fixed id';
185
+ res.body.name = res.body.name.toLowerCase();
186
+ })
187
+ .expect(200, {
188
+ id: 'some fixed id',
189
+ name: 'john'
190
+ }, done);
191
+ });
192
+ });
193
+ ```
194
+
195
+ Anything you can do with superagent, you can do with supertest - for example multipart file uploads!
196
+
197
+ ```js
198
+ request(app)
199
+ .post('/')
200
+ .field('name', 'my awesome avatar')
201
+ .field('complex_object', '{"attribute": "value"}', {contentType: 'application/json'})
202
+ .attach('avatar', 'test/fixtures/avatar.jpg')
203
+ ...
204
+ ```
205
+
206
+ Passing the app or url each time is not necessary, if you're testing
207
+ the same host you may simply re-assign the request variable with the
208
+ initialization app or url, a new `Test` is created per `request.VERB()` call.
209
+
210
+ ```js
211
+ request = request('http://localhost:5555');
212
+
213
+ request.get('/').expect(200, function(err){
214
+ console.log(err);
215
+ });
216
+
217
+ request.get('/').expect('heya', function(err){
218
+ console.log(err);
219
+ });
220
+ ```
221
+
222
+ Here's an example with mocha that shows how to persist a request and its cookies:
223
+
224
+ ```js
225
+ const request = require('supertest');
226
+ const should = require('should');
227
+ const express = require('express');
228
+ const cookieParser = require('cookie-parser');
229
+
230
+ describe('request.agent(app)', function() {
231
+ const app = express();
232
+ app.use(cookieParser());
233
+
234
+ app.get('/', function(req, res) {
235
+ res.cookie('cookie', 'hey');
236
+ res.send();
237
+ });
238
+
239
+ app.get('/return', function(req, res) {
240
+ if (req.cookies.cookie) res.send(req.cookies.cookie);
241
+ else res.send(':(')
242
+ });
243
+
244
+ const agent = request.agent(app);
245
+
246
+ it('should save cookies', function(done) {
247
+ agent
248
+ .get('/')
249
+ .expect('set-cookie', 'cookie=hey; Path=/', done);
250
+ });
251
+
252
+ it('should send cookies', function(done) {
253
+ agent
254
+ .get('/return')
255
+ .expect('hey', done);
256
+ });
257
+ });
258
+ ```
259
+
260
+ There is another example that is introduced by the file [agency.js](https://github.com/ladjs/superagent/blob/master/test/node/agency.js)
261
+
262
+ Here is an example where 2 cookies are set on the request.
263
+
264
+ ```js
265
+ agent(app)
266
+ .get('/api/content')
267
+ .set('Cookie', ['nameOne=valueOne;nameTwo=valueTwo'])
268
+ .send()
269
+ .expect(200)
270
+ .end((err, res) => {
271
+ if (err) {
272
+ return done(err);
273
+ }
274
+ expect(res.text).to.be.equal('hey');
275
+ return done();
276
+ });
277
+ ```
278
+
279
+ ## API
280
+
281
+ You may use any [superagent](http://github.com/ladjs/superagent) methods,
282
+ including `.write()`, `.pipe()` etc and perform assertions in the `.end()` callback
283
+ for lower-level needs.
284
+
285
+ ### .expect(status[, fn])
286
+
287
+ Assert response `status` code.
288
+
289
+ ### .expect(status, body[, fn])
290
+
291
+ Assert response `status` code and `body`.
292
+
293
+ ### .expect(body[, fn])
294
+
295
+ Assert response `body` text with a string, regular expression, or
296
+ parsed body object.
297
+
298
+ ### .expect(field, value[, fn])
299
+
300
+ Assert header `field` `value` with a string or regular expression.
301
+
302
+ ### .expect(function(res) {})
303
+
304
+ Pass a custom assertion function. It'll be given the response object to check. If the check fails, throw an error.
305
+
306
+ ```js
307
+ request(app)
308
+ .get('/')
309
+ .expect(hasPreviousAndNextKeys)
310
+ .end(done);
311
+
312
+ function hasPreviousAndNextKeys(res) {
313
+ if (!('next' in res.body)) throw new Error("missing next key");
314
+ if (!('prev' in res.body)) throw new Error("missing prev key");
315
+ }
316
+ ```
317
+
318
+ ### .end(fn)
319
+
320
+ Perform the request and invoke `fn(err, res)`.
321
+
322
+ ## Cookies
323
+
324
+ Here is an example of using the `set` and `not` cookie assertions:
325
+
326
+ ```js
327
+ // setup super-test
328
+ const request = require('supertest');
329
+ const express = require('express');
330
+ const cookies = request.cookies;
331
+
332
+ // setup express test service
333
+ const app = express();
334
+
335
+ app.get('/users', function(req, res) {
336
+ res.cookie('alpha', 'one', { domain: 'domain.com', path: '/', httpOnly: true });
337
+ res.send(200, { name: 'tobi' });
338
+ });
339
+
340
+ // test request to service
341
+ request(app)
342
+ .get('/users')
343
+ .expect('Content-Type', /json/)
344
+ .expect('Content-Length', '15')
345
+ .expect(200)
346
+ // assert 'alpha' cookie is set with domain, path, and httpOnly options
347
+ .expect(cookies.set({ name: 'alpha', options: ['domain', 'path', 'httponly'] }))
348
+ // assert 'bravo' cookie is NOT set
349
+ .expect(cookies.not('set', { name: 'bravo' }))
350
+ .end(function(err, res) {
351
+ if (err) {
352
+ throw err;
353
+ }
354
+ });
355
+ ```
356
+
357
+ It is also possible to chain assertions:
358
+
359
+ ```js
360
+ cookies.set({/* ... */}).not('set', {/* ... */})
361
+ ```
362
+
363
+ ### Cookie assertions
364
+
365
+ Functions and methods are chainable.
366
+
367
+ #### cookies([secret], [asserts])
368
+
369
+ Get assertion function for [super-test](https://github.com/visionmedia/supertest) `.expect()` method.
370
+
371
+ *Arguments*
372
+
373
+ - `secret` - String or array of strings. Cookie signature secrets.
374
+ - `asserts(req, res)` - Function or array of functions. Failed custom assertions should throw.
375
+
376
+ #### .set(expects, [assert])
377
+
378
+ Assert that cookie and options are set.
379
+
380
+ *Arguments*
381
+
382
+ - `expects` - Object or array of objects.
383
+ - `name` - String name of cookie.
384
+ - `options` - *Optional* array of options.
385
+ - `assert` - *Optional* boolean "assert true" modifier. Default: `true`.
386
+
387
+ #### .reset(expects, [assert])
388
+
389
+ Assert that cookie is set and was already set (in request headers).
390
+
391
+ *Arguments*
392
+
393
+ - `expects` - Object or array of objects.
394
+ - `name` - String name of cookie.
395
+ - `assert` - *Optional* boolean "assert true" modifier. Default: `true`.
396
+
397
+ #### .new(expects, [assert])
398
+
399
+ Assert that cookie is set and was NOT already set (NOT in request headers).
400
+
401
+ *Arguments*
402
+
403
+ - `expects` - Object or array of objects.
404
+ - `name` - String name of cookie.
405
+ - `assert` - *Optional* boolean "assert true" modifier. Default: `true`.
406
+
407
+ #### .renew(expects, [assert])
408
+
409
+ Assert that cookie is set with a strictly greater `expires` or `max-age` than the given value.
410
+
411
+ *Arguments*
412
+
413
+ - `expects` - Object or array of objects.
414
+ - `name` - String name of cookie.
415
+ - `options` - Object of options. `use one of two options below`
416
+ - `options`.`expires` - String UTC expiration for original cookie (in request headers).
417
+ - `options`.`max-age` - Integer ttl in seconds for original cookie (in request headers).
418
+ - `assert` - *Optional* boolean "assert true" modifier. Default: `true`.
419
+
420
+ #### .contain(expects, [assert])
421
+
422
+ Assert that cookie is set with value and contains options.
423
+
424
+ Requires `cookies(secret)` initialization if cookie is signed.
425
+
426
+ *Arguments*
427
+
428
+ - `expects` - Object or array of objects.
429
+ - `name` - String name of cookie.
430
+ - `value` - *Optional* string unsigned value of cookie.
431
+ - `options` - *Optional* object of options.
432
+ - `options`.`domain` - *Optional* string domain.
433
+ - `options`.`path` - *Optional* string path.
434
+ - `options`.`expires` - *Optional* string UTC expiration.
435
+ - `options`.`max-age` - *Optional* integer ttl, in seconds.
436
+ - `options`.`secure` - *Optional* boolean secure flag.
437
+ - `options`.`httponly` - *Optional* boolean httpOnly flag.
438
+ - `assert` - *Optional* boolean "assert true" modifier. Default: `true`.
439
+
440
+ #### .not(method, expects)
441
+
442
+ Call any cookies assertion method with "assert true" modifier set to `false`.
443
+
444
+ Syntactic sugar.
445
+
446
+ *Arguments*
447
+
448
+ - `method` - String method name. Arguments of method name apply in `expects`.
449
+ - `expects` - Object or array of objects.
450
+ - `name` - String name of cookie.
451
+ - `value` - *Optional* string unsigned value of cookie.
452
+ - `options` - *Optional* object of options.
453
+
454
+ ## Notes
455
+
456
+ Inspired by [api-easy](https://github.com/flatiron/api-easy) minus vows coupling.
457
+
458
+ ## License
459
+
460
+ MIT
461
+
462
+ [coverage-badge]: https://img.shields.io/codecov/c/github/ladjs/supertest.svg
463
+ [coverage]: https://codecov.io/gh/ladjs/supertest
464
+ [travis-badge]: https://travis-ci.org/ladjs/supertest.svg?branch=master
465
+ [travis]: https://travis-ci.org/ladjs/supertest
466
+ [dependencies-badge]: https://david-dm.org/ladjs/supertest/status.svg
467
+ [dependencies]: https://david-dm.org/ladjs/supertest
468
+ [prs-badge]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square
469
+ [prs]: http://makeapullrequest.com
470
+ [license-badge]: https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square
471
+ [license]: https://github.com/ladjs/supertest/blob/master/LICENSE
package/index.js ADDED
@@ -0,0 +1,67 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Module dependencies.
5
+ */
6
+ const methods = require('methods');
7
+ let http2;
8
+ try {
9
+ http2 = require('http2'); // eslint-disable-line global-require
10
+ } catch (_) {
11
+ // eslint-disable-line no-empty
12
+ }
13
+ const Test = require('./lib/test.js');
14
+ const agent = require('./lib/agent.js');
15
+ const cookies = require('./lib/cookies');
16
+
17
+ /**
18
+ * Test against the given `app`,
19
+ * returning a new `Test`.
20
+ *
21
+ * @param {Function|Server|String} app
22
+ * @return {Test}
23
+ * @api public
24
+ */
25
+ module.exports = function(app, options = {}) {
26
+ const obj = {};
27
+
28
+ if (typeof app === 'function') {
29
+ if (options.http2) {
30
+ if (!http2) {
31
+ throw new Error(
32
+ 'supertest: this version of Node.js does not support http2'
33
+ );
34
+ }
35
+ }
36
+ }
37
+
38
+ methods.forEach(function(method) {
39
+ obj[method] = function(url) {
40
+ var test = new Test(app, method, url, options.http2);
41
+ if (options.http2) {
42
+ test.http2();
43
+ }
44
+ return test;
45
+ };
46
+ });
47
+
48
+ // Support previous use of del
49
+ obj.del = obj.delete;
50
+
51
+ return obj;
52
+ };
53
+
54
+ /**
55
+ * Expose `Test`
56
+ */
57
+ module.exports.Test = Test;
58
+
59
+ /**
60
+ * Expose the agent function
61
+ */
62
+ module.exports.agent = agent;
63
+
64
+ /**
65
+ * Expose cookie assertions
66
+ */
67
+ module.exports.cookies = cookies;
package/lib/agent.js ADDED
@@ -0,0 +1,100 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Module dependencies.
5
+ */
6
+
7
+ const { agent: Agent } = require('superagent');
8
+ const methods = require('methods');
9
+ const http = require('http');
10
+ let http2;
11
+ try {
12
+ http2 = require('http2'); // eslint-disable-line global-require
13
+ } catch (_) {
14
+ // eslint-disable-line no-empty
15
+ }
16
+ const Test = require('./test.js');
17
+
18
+ /**
19
+ * Initialize a new `TestAgent`.
20
+ *
21
+ * @param {Function|Server} app
22
+ * @param {Object} options
23
+ * @api public
24
+ */
25
+
26
+ function TestAgent(app, options = {}) {
27
+ if (!(this instanceof TestAgent)) return new TestAgent(app, options);
28
+
29
+ const agent = new Agent(options);
30
+ Object.assign(this, agent);
31
+
32
+ this._options = options;
33
+
34
+ if (typeof app === 'function') {
35
+ if (options.http2) {
36
+ if (!http2) {
37
+ throw new Error(
38
+ 'supertest: this version of Node.js does not support http2'
39
+ );
40
+ }
41
+ app = http2.createServer(app); // eslint-disable-line no-param-reassign
42
+ } else {
43
+ app = http.createServer(app); // eslint-disable-line no-param-reassign
44
+ }
45
+ }
46
+ this.app = app;
47
+ }
48
+
49
+ /**
50
+ * Inherits from `Agent.prototype`.
51
+ */
52
+
53
+ Object.setPrototypeOf(TestAgent.prototype, Agent.prototype);
54
+
55
+ // Preserve the original query method before overriding HTTP methods
56
+ const originalQuery = Agent.prototype.query;
57
+
58
+ // set a host name
59
+ TestAgent.prototype.host = function(host) {
60
+ this._host = host;
61
+ return this;
62
+ };
63
+
64
+ // override HTTP verb methods
65
+ methods.forEach(function(method) {
66
+ // Skip 'query' method to prevent overwriting superagent's query functionality
67
+ if (method === 'query') {
68
+ return;
69
+ }
70
+
71
+ TestAgent.prototype[method] = function(url, fn) { // eslint-disable-line no-unused-vars
72
+ const req = new Test(this.app, method.toUpperCase(), url);
73
+ if (this._options.http2) {
74
+ req.http2();
75
+ }
76
+
77
+ if (this._host) {
78
+ req.set('host', this._host);
79
+ }
80
+
81
+ req.on('response', this._saveCookies.bind(this));
82
+ req.on('redirect', this._saveCookies.bind(this));
83
+ req.on('redirect', this._attachCookies.bind(this, req));
84
+ this._setDefaults(req);
85
+ this._attachCookies(req);
86
+
87
+ return req;
88
+ };
89
+ });
90
+
91
+ // Restore the original query method
92
+ TestAgent.prototype.query = originalQuery;
93
+
94
+ TestAgent.prototype.del = TestAgent.prototype.delete;
95
+
96
+ /**
97
+ * Expose `Agent`.
98
+ */
99
+
100
+ module.exports = TestAgent;