UNPKG

1.93 kBJavaScriptView Raw
1'use strict';
2
3/**
4 * Module dependencies.
5 */
6
7const { agent: Agent } = require('superagent');
8const methods = require('methods');
9const http = require('http');
10let http2;
11try {
12 http2 = require('http2'); // eslint-disable-line global-require
13} catch (_) {
14 // eslint-disable-line no-empty
15}
16const 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
26function 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); // eslint-disable-line no-param-reassign
40 } else {
41 app = http.createServer(app); // eslint-disable-line no-param-reassign
42 }
43 }
44 this.app = app;
45}
46
47/**
48 * Inherits from `Agent.prototype`.
49 */
50
51Object.setPrototypeOf(TestAgent.prototype, Agent.prototype);
52
53// set a host name
54TestAgent.prototype.host = function(host) {
55 this._host = host;
56 return this;
57};
58
59// override HTTP verb methods
60methods.forEach(function(method) {
61 TestAgent.prototype[method] = function(url, fn) { // eslint-disable-line no-unused-vars
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
81TestAgent.prototype.del = TestAgent.prototype.delete;
82
83/**
84 * Expose `Agent`.
85 */
86
87module.exports = TestAgent;