UNPKG

1.62 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');
10const Test = require('./test.js');
11
12/**
13 * Initialize a new `TestAgent`.
14 *
15 * @param {Function|Server} app
16 * @param {Object} options
17 * @api public
18 */
19
20function TestAgent(app, options) {
21 if (!(this instanceof TestAgent)) return new TestAgent(app, options);
22 if (typeof app === 'function') app = http.createServer(app); // eslint-disable-line no-param-reassign
23 if (options) {
24 this._ca = options.ca;
25 this._key = options.key;
26 this._cert = options.cert;
27 }
28 Agent.call(this);
29 this.app = app;
30}
31
32/**
33 * Inherits from `Agent.prototype`.
34 */
35
36Object.setPrototypeOf(TestAgent.prototype, Agent.prototype);
37
38// set a host name
39TestAgent.prototype.host = function(host) {
40 this._host = host;
41 return this;
42};
43
44// override HTTP verb methods
45methods.forEach(function(method) {
46 TestAgent.prototype[method] = function(url, fn) { // eslint-disable-line no-unused-vars
47 const req = new Test(this.app, method.toUpperCase(), url, this._host);
48 req.ca(this._ca);
49 req.cert(this._cert);
50 req.key(this._key);
51 if (this._host) {
52 req.set('host', this._host);
53 }
54
55 req.on('response', this._saveCookies.bind(this));
56 req.on('redirect', this._saveCookies.bind(this));
57 req.on('redirect', this._attachCookies.bind(this, req));
58 this._attachCookies(req);
59 this._setDefaults(req);
60
61 return req;
62 };
63});
64
65TestAgent.prototype.del = TestAgent.prototype.delete;
66
67/**
68 * Expose `Agent`.
69 */
70
71module.exports = TestAgent;