如何在Mocha测试用例中发送标题(“授权”,“承载者令牌”) [英] How to send Headers ('Authorization','Bearer token') in Mocha Test cases
问题描述
我正在编写一个测试用例来测试我的API。当我尝试测试任何开放的API时,它工作正常。但是,当我尝试将授权令牌和我的API一起发送时,它不起作用。这是代码:
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:
我发送标头的方式是:
。 set( Authorization, Bearer +令牌)
发送方法是否正确?
我尝试在Auth中发送授权令牌。但无法获得相同的结果。但是,当我尝试在邮递员中消费时,效果很好。
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();
});
});
推荐答案
我喜欢以以下方式设置测试:
I like to set up my tests in the following way:
let baseUrl = 'http://localhost:9090'
let token = 'some_authorization_token'
首先,我将实例化变量 baseUrl
和 token
(位于测试的最顶部),紧接在 use()
部分之后。
First I would instantiate my variables baseUrl
and token
at the very top of the test, right after use()
part.
接下来是测试的设置。
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))
});
现在, .set()
不会'不一定必须像我的一样,在您的情况下也适用。
Now, .set()
doesn't necessarily have to be like mine, works in your case as well.
这篇关于如何在Mocha测试用例中发送标题(“授权”,“承载者令牌”)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!