agent.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /**
  2. * Module dependencies.
  3. */
  4. var Agent = require('superagent').agent;
  5. var methods = require('methods');
  6. var http = require('http');
  7. var Test = require('./test');
  8. /**
  9. * Expose `Agent`.
  10. */
  11. module.exports = TestAgent;
  12. /**
  13. * Initialize a new `TestAgent`.
  14. *
  15. * @param {Function|Server} app
  16. * @param {Object} options
  17. * @api public
  18. */
  19. function TestAgent(app, options) {
  20. if (!(this instanceof TestAgent)) return new TestAgent(app, options);
  21. if (typeof app === 'function') app = http.createServer(app); // eslint-disable-line no-param-reassign
  22. if (options) {
  23. this._ca = options.ca;
  24. this._key = options.key;
  25. this._cert = options.cert;
  26. }
  27. Agent.call(this);
  28. this.app = app;
  29. }
  30. /**
  31. * Inherits from `Agent.prototype`.
  32. */
  33. Object.setPrototypeOf(TestAgent.prototype, Agent.prototype);
  34. // set a host name
  35. TestAgent.prototype.host = function(host) {
  36. this._host = host;
  37. return this;
  38. };
  39. // override HTTP verb methods
  40. methods.forEach(function(method) {
  41. TestAgent.prototype[method] = function(url, fn) { // eslint-disable-line no-unused-vars
  42. var req = new Test(this.app, method.toUpperCase(), url, this._host);
  43. req.ca(this._ca);
  44. req.cert(this._cert);
  45. req.key(this._key);
  46. req.on('response', this._saveCookies.bind(this));
  47. req.on('redirect', this._saveCookies.bind(this));
  48. req.on('redirect', this._attachCookies.bind(this, req));
  49. this._attachCookies(req);
  50. this._setDefaults(req);
  51. return req;
  52. };
  53. });
  54. TestAgent.prototype.del = TestAgent.prototype.delete;