问题
I am writing a test case to test my API . When I try to test for any open API, it is working fine. But When I try to send Authorization Token along with my API, it is not working. Here is the code:
The way i am sending headers is:
.set("Authorization", "Bearer " + token)
Is it the correct way of sending?
I have tried to send the Authorization token in Auth. But not able to get the same. But when I tried to consume same in Postman, it is working fine.
it("Get some random Info", function(done) {
chai
.request(baseUrl)
.get("/someRandomApi")
.set("Authorization", "Bearer " + token)
.end(function(err, res) {
expect(res).to.have.status(200);
done();
});
});
回答1:
I like to set up my tests in the following way:
let baseUrl = 'http://localhost:9090'
let token = 'some_authorization_token'
First I would instantiate my variables baseUrl
and token
at the very top of the test, right after use()
part.
Next to come is the setup of the test.
it("Get some random Info", function(done) {
chai.request(baseUrl)
.get('/someRandomApi')
.set({ "Authorization": `Bearer ${token}` })
.then((res) => {
expect(res).to.have.status(200)
const body = res.body
// console.log(body) - not really needed, but I include them as a comment
done();
}).catch((err) => done(err))
});
Now, .set()
doesn't necessarily have to be like mine, works in your case as well.
回答2:
Try calling .get()
after you call .set()
:
it("Get some random Info", function(done) {
chai
.request(baseUrl)
.set("Authorization", "Bearer " + token) //set the header first
.get("/someRandomApi") //then get the data
.end(function(err, res) {
expect(res).to.have.status(200);
done();
});
});
来源:https://stackoverflow.com/questions/57668262/how-to-send-headers-authorization-bearer-token-in-mocha-test-cases