From 7cab097f7d291c2a7ed1a2ebca852b93b036a41f Mon Sep 17 00:00:00 2001 From: Mark Stosberg Date: Mon, 10 Sep 2018 10:01:35 -0400 Subject: [PATCH] Support setting other defaults in the re-usable agent besides cookies. Since `superagent` 3.8, there has been support for the re-usable agent supporting other defaults besides cookies. For example, it's particularly useful to set default 'Authorization' header before running repeated tests against an authenticated API. I tracked down which version of `superagent` we needed to use as a minimum dependency to this commit: https://github.com/visionmedia/superagent/commit/66aed3427f29bf0c09b1df0e7f8aa9f0e30732ab This update should be considered a bug fix, as 'supertest' claims to support all of superagent's features, but this feature is documented in superagent, but wasn't working in `supertest'. --- README.md | 10 ++++++++++ lib/agent.js | 1 + test/supertest.js | 18 ++++++++++++++++++ 3 files changed, 29 insertions(+) diff --git a/README.md b/README.md index 1a2183ac..8a3707d6 100644 --- a/README.md +++ b/README.md @@ -188,6 +188,16 @@ describe('request.agent(app)', function() { .expect('hey', done); }); }) + +Another use could be to automatically send an Authorization header by default: + + + var apiAgent = request.agent(app).set('Authorization', 'Bearer SOMETOKEN'); + + // Now run lots of tests against API that requires authetnication. + apiAgent.get(...) + + ``` There is another example that is introduced by the file [agency.js](https://github.com/visionmedia/superagent/blob/master/test/node/agency.js) diff --git a/lib/agent.js b/lib/agent.js index 54ce47f1..16c9560a 100644 --- a/lib/agent.js +++ b/lib/agent.js @@ -58,6 +58,7 @@ methods.forEach(function(method) { req.on('redirect', this._saveCookies.bind(this)); req.on('redirect', this._attachCookies.bind(this, req)); this._attachCookies(req); + this._setDefaults(req); return req; }; diff --git a/test/supertest.js b/test/supertest.js index af708780..03ab747b 100644 --- a/test/supertest.js +++ b/test/supertest.js @@ -847,6 +847,15 @@ describe('request.agent(app)', function () { else res.send(':('); }); + // Echo back the authorization header we receive to test set() defaults + app.get('/set', function(req, res) { + if (req.get('authorization')) { + res.send(req.get('authorization')); + } else { + res.send(':('); + } + }); + it('should save cookies', function (done) { agent .get('/') @@ -858,6 +867,15 @@ describe('request.agent(app)', function () { .get('/return') .expect('hey', done); }); + + + it('should support set() defaults', function(done) { + var defaultsAgent = request.agent(app).set('Authorization', 'Bearer'); + + defaultsAgent + .get('/set') + .expect('Bearer', done); + }); }); describe('agent.host(host)', function () {