request(app)
.post('/api/categories')
.send(category)
.set({ Authorization: token })
.end((err, res) => {
const newCategory = res.body;
expect(res.status).to.be.equal(200);
expect(newCategory).to.be.equal(category);
done();
});
Error:
Error: "value" required in setHeader("Authorization", value)
request(app)
.post('/api/categories')
.send(category)
.setHeader('Authorization', token)
.end((err, res) => {
const newCategory = res.body;
expect(res.status).to.be.equal(200);
expect(newCategory).to.be.equal(category);
done();
});
Error:
TypeError: (0 , _supertest2.default)(...).post(...).send(...).setHeader is not a function
How set header to post request ?
You do want to use the .set function.
You should be able to pass a single JSON object or two parameters for the key and value.
.set('Accept', 'application/json')
.set({ 'API-Key': 'foobar', Accept: 'application/json' })
In your first example I would say that there is a problem with the variable token.
this does not work.
Note that you have to call .set() AFTER calling .post(), not before. For example:
request(app)
.set('Authorization', 'abc123') // DOES NOT WORK
.post('/api')
request(app)
.post('/api')
.set('Authorization', 'abc123') // Works.
Note that you have to call
.set()AFTER calling.post(), not before. For example:request(app) .set('Authorization', 'abc123') // DOES NOT WORK .post('/api') request(app) .post('/api') .set('Authorization', 'abc123') // Works.
It's TERRIBLE !!!
Suppose i have multiple routes to test, which all are protected by same authentication middleware ( using headers). This way, I have to set header independently for all of them!!
Note that you have to call
.set()AFTER calling.post(), not before. For example:request(app) .set('Authorization', 'abc123') // DOES NOT WORK .post('/api') request(app) .post('/api') .set('Authorization', 'abc123') // Works.It's TERRIBLE !!!
Suppose i have multiple routes to test, which all are protected by same authentication middleware ( using headers). This way, I have to set header independently for all of them!!
Well it would only make sense to do that since in a real-life scenario you are making separate HTTP Requests, each having its own separate Header. Unless I understood you wrong?
@christopheelkhoury In a real-life app, i would set auth header in state and create a new instance of HttpRequest which hold the auth header. For example this is my HttpService:
export default () => {
return axios.create({
baseURL: `${config.BASE_URL}/${config.API_VERSION}`,
headers: {
'blog-admin': store.state.Auth.token || '',
'Cache-Control': 'no-cache'
}
})
}
And i'll call it like:
export function index() {
return Http().get('/posts')
}
So there is no duplication of code and i can change header or auth method easily by changing one line of code. But the syntax in super test makes me to set header separately for each request which is not clean and not DRY
@JafarAkhondali If you are talking about setting up the header for multiple routes then you can do something like make function which will execute before all the test case and freom there get that header value and set it in others routes so in that way you dont have to write the same request code all the time whereas only thing you have to do is to set the value using .set('Authorization', value)
Example: -
var loggedInToken = '';
before((done)=>{
chai.request(server)
.post('/api/users/login')
.send({
email: email,
password: password
})
.end((err, response)=>{
loggedInToken = response.body.token;
done();
});
});
now use that set() in all the routes
Hope this helps.
Separe the request logic from all your tests simulating supertest(url).method()
const URL = `My Endpoint`;
const TOKEN = 'Secret';
const hook = (method = 'post') => (args) =>
supertest(URL)
[method](args)
.set('Authorization', `Basic ${TOKEN}`);
const request = {
post: hook('post'),
get: hook('get'),
put: hook('put'),
delete: hook('delete'),
};
export default request;
I dont touch my tests code
I'm trying to set header but is not part of the headers
await request(app)
.get('/user/all')
.set({
Authorization: 'abc123',
})
.expect(({ headers }) => {
console.log(headers);
})
.expect(HttpStatus.BAD_REQUEST);
This is the headers object:
{
'content-security-policy': "default-src 'self';base-uri 'self';block-all-mixed-content;font-src 'self' https: data:;frame-ancestors 'self';img-src 'self' data:;object-src 'none';script-src 'self';script-src-attr 'none';style-src 'self' https: 'unsafe-inline';upgrade-insecure-requests",
'x-dns-prefetch-control': 'off',
'expect-ct': 'max-age=0',
'x-frame-options': 'SAMEORIGIN',
'strict-transport-security': 'max-age=15552000; includeSubDomains',
'x-download-options': 'noopen',
'x-content-type-options': 'nosniff',
'x-permitted-cross-domain-policies': 'none',
'referrer-policy': 'no-referrer',
'x-xss-protection': '0',
'access-control-allow-origin': '*',
'content-type': 'application/json; charset=utf-8',
'content-length': '43',
etag: 'W/"2b-hGShxOkieaAVDloBubJVM+h58D8"',
date: 'Thu, 17 Dec 2020 11:07:30 GMT',
connection: 'close'
}
Any idea how to append Authorization to the headers?
I also tried .set(Authorization, 'abc123')
I'm trying to set header but is not part of the headers
await request(app) .get('/user/all') .set({ Authorization: 'abc123', }) .expect(({ headers }) => { console.log(headers); }) .expect(HttpStatus.BAD_REQUEST);This is the headers object:
{ 'content-security-policy': "default-src 'self';base-uri 'self';block-all-mixed-content;font-src 'self' https: data:;frame-ancestors 'self';img-src 'self' data:;object-src 'none';script-src 'self';script-src-attr 'none';style-src 'self' https: 'unsafe-inline';upgrade-insecure-requests", 'x-dns-prefetch-control': 'off', 'expect-ct': 'max-age=0', 'x-frame-options': 'SAMEORIGIN', 'strict-transport-security': 'max-age=15552000; includeSubDomains', 'x-download-options': 'noopen', 'x-content-type-options': 'nosniff', 'x-permitted-cross-domain-policies': 'none', 'referrer-policy': 'no-referrer', 'x-xss-protection': '0', 'access-control-allow-origin': '*', 'content-type': 'application/json; charset=utf-8', 'content-length': '43', etag: 'W/"2b-hGShxOkieaAVDloBubJVM+h58D8"', date: 'Thu, 17 Dec 2020 11:07:30 GMT', connection: 'close' }Any idea how to append Authorization to the headers?
I also tried .set(Authorization, 'abc123')
@AndonMitev I'm guessing you're using the request package.
If that's the case, I'd recommend you construct the request object before sending it, making your code as such:
const options = {
uri: <YOUR_URL>,
method: 'GET',
headers: {
'Auhorization': 'Bearer <TOKEN>'
}
};
await request(options)
.expect(({ headers }) => {
console.log(headers);
})
.expect(HttpStatus.BAD_REQUEST);
I'm trying to set header but is not part of the headers
await request(app) .get('/user/all') .set({ Authorization: 'abc123', }) .expect(({ headers }) => { console.log(headers); }) .expect(HttpStatus.BAD_REQUEST);This is the headers object:
{ 'content-security-policy': "default-src 'self';base-uri 'self';block-all-mixed-content;font-src 'self' https: data:;frame-ancestors 'self';img-src 'self' data:;object-src 'none';script-src 'self';script-src-attr 'none';style-src 'self' https: 'unsafe-inline';upgrade-insecure-requests", 'x-dns-prefetch-control': 'off', 'expect-ct': 'max-age=0', 'x-frame-options': 'SAMEORIGIN', 'strict-transport-security': 'max-age=15552000; includeSubDomains', 'x-download-options': 'noopen', 'x-content-type-options': 'nosniff', 'x-permitted-cross-domain-policies': 'none', 'referrer-policy': 'no-referrer', 'x-xss-protection': '0', 'access-control-allow-origin': '*', 'content-type': 'application/json; charset=utf-8', 'content-length': '43', etag: 'W/"2b-hGShxOkieaAVDloBubJVM+h58D8"', date: 'Thu, 17 Dec 2020 11:07:30 GMT', connection: 'close' }Any idea how to append Authorization to the headers?
I also tried .set(Authorization, 'abc123')
// if you setup ur server to response with a token after a login operation u can authorize the get/post individual operation as follow .N.B // token = a string sent back as response header to the browser by a server
await request(app)
.get('/user/all') .auth(token, {type:'bearer'} ) }) .expect(({ headers }) => { console.log(headers);
Note that you have to call
.set()AFTER calling.post(), not before. For example:request(app) .set('Authorization', 'abc123') // DOES NOT WORK .post('/api') request(app) .post('/api') .set('Authorization', 'abc123') // Works.It's TERRIBLE !!!
Suppose i have multiple routes to test, which all are protected by same authentication middleware ( using headers). This way, I have to set header independently for all of them!!Well it would only make sense to do that since in a real-life scenario you are making separate HTTP Requests, each having its own separate Header. Unless I understood you wrong?
Sometimes - eg while running integration tests - it completely makes sense to set same headers for all requests.
In my case I would like to create a factory method which returns supertest agent with default headers but because headers are reseted when .post() is called, it is not easily possible..
Most helpful comment
Note that you have to call
.set()AFTER calling.post(), not before. For example: