1 | 'use strict';
|
2 |
|
3 |
|
4 |
|
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');
|
13 | } catch (_) {
|
14 |
|
15 | }
|
16 | const Test = require('./test.js');
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 | function TestAgent(app, options = {}) {
|
27 | if (!(this instanceof TestAgent)) return new TestAgent(app, options);
|
28 |
|
29 | Agent.call(this, options);
|
30 | this._options = options;
|
31 |
|
32 | if (typeof app === 'function') {
|
33 | if (options.http2) {
|
34 | if (!http2) {
|
35 | throw new Error(
|
36 | 'supertest: this version of Node.js does not support http2'
|
37 | );
|
38 | }
|
39 | app = http2.createServer(app);
|
40 | } else {
|
41 | app = http.createServer(app);
|
42 | }
|
43 | }
|
44 | this.app = app;
|
45 | }
|
46 |
|
47 |
|
48 |
|
49 |
|
50 |
|
51 | Object.setPrototypeOf(TestAgent.prototype, Agent.prototype);
|
52 |
|
53 |
|
54 | TestAgent.prototype.host = function(host) {
|
55 | this._host = host;
|
56 | return this;
|
57 | };
|
58 |
|
59 |
|
60 | methods.forEach(function(method) {
|
61 | TestAgent.prototype[method] = function(url, fn) {
|
62 | const req = new Test(this.app, method.toUpperCase(), url);
|
63 | if (this._options.http2) {
|
64 | req.http2();
|
65 | }
|
66 |
|
67 | if (this._host) {
|
68 | req.set('host', this._host);
|
69 | }
|
70 |
|
71 | req.on('response', this._saveCookies.bind(this));
|
72 | req.on('redirect', this._saveCookies.bind(this));
|
73 | req.on('redirect', this._attachCookies.bind(this, req));
|
74 | this._setDefaults(req);
|
75 | this._attachCookies(req);
|
76 |
|
77 | return req;
|
78 | };
|
79 | });
|
80 |
|
81 | TestAgent.prototype.del = TestAgent.prototype.delete;
|
82 |
|
83 |
|
84 |
|
85 |
|
86 |
|
87 | module.exports = TestAgent;
|