Skip to content

Commit

Permalink
Support setting other defaults in the re-usable agent besides cookies.
Browse files Browse the repository at this point in the history
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:

ladjs/superagent@66aed34

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'.
  • Loading branch information
markstos committed Dec 28, 2017
1 parent 199506d commit 4d9057b
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 1 deletion.
10 changes: 10 additions & 0 deletions Readme.md
Expand Up @@ -180,6 +180,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)

Expand Down
1 change: 1 addition & 0 deletions lib/agent.js
Expand Up @@ -52,6 +52,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;
};
Expand Down
2 changes: 1 addition & 1 deletion package.json
Expand Up @@ -8,7 +8,7 @@
"test": "eslint lib/**/*.js test/**/*.js && mocha --require should --reporter spec --check-leaks"
},
"dependencies": {
"superagent": "^3.0.0",
"superagent": "^3.8.0",
"methods": "~1.1.2"
},
"devDependencies": {
Expand Down
18 changes: 18 additions & 0 deletions test/supertest.js
Expand Up @@ -802,6 +802,16 @@ 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('/')
Expand All @@ -813,6 +823,14 @@ 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('.<http verb> works as expected', function() {
Expand Down

0 comments on commit 4d9057b

Please sign in to comment.