With Supertest, can I create an alternative request with some headers set by default?
If i remember correctly in superagent one can pass a hash to set
agent.set({key:value,key2:value2})
let me know if it doesnt work with supertest.
You could use a common routine to build your "default" headers as an object and pass them to the request:
//# file:config.js
var config = {
authorization: { "Authorization":"authvalue" }
}
// Content-Type left out because supertest will use Content-Type json when you use the appropriate method
module.exports = config;
And now in your test.js:
//# file:test.js
var request = require("supertest");
var config = require("./config");
request = request(config.baseUrl)
var commonHeaders = { "authorization":"TokenValueASDF" };
describe("testing", function() {
it.should('present authorization header to server', function(done) {
request.get('/someurl')
.set(commonHeaders)
.set({"X-TestSpecificHeader":"Value"})
.expect(200,done) //if not authorized you'd get 401
})
})
Also, if you need to have your app get that token value at runtime (most likely) see this article for using a requested token value that is generated for the tests: https://jaketrent.com/post/authenticated-supertest-tests/
You can use the library superagent-defaults
as follows:
installation
npm install --save-dev supertest superagent-defaults
usage
var defaults = require('superagent-defaults');
var supertest = require('supertest');
var request = defaults(supertest(app)); // or url
// set the default headers
request.set(commonHeaders);
// use as usually
version
- supertest v3.0.0
- superagent-defaults v0.1.14