我正在编写一个测试用例来测试我的 API 。当我尝试测试任何开放 API 时,它工作正常。但是当我尝试将授权 token 与我的 API 一起发送时,它不起作用。这是代码:
我发送 header 的方式是:
.set("授权", "承载者"+ token )
这是正确的发送方式吗?
我尝试在 Auth 中发送授权 token 。但无法获得相同的结果。但是当我尝试在 Postman 中使用相同的内容时,它工作正常。
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();
});
});
最佳答案
我喜欢通过以下方式设置我的测试:
let baseUrl = 'http://localhost:9090'
let token = 'some_authorization_token'
首先,我将在测试的最顶部、use()
部分之后实例化我的变量 baseUrl
和 token
。
接下来是测试的设置。
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()
不一定必须像我的那样,也适用于您的情况。
关于javascript - 如何在 Mocha 测试用例中发送 header ('Authorization' ,'Bearer token' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57668262/