[英]What is the proper way to test routes secured with jwt token?
While the following test passes I feel I'm doing this wrong.虽然以下测试通过了,但我觉得我做错了。 Am I expected to log in every time i need to test a secure route?我每次需要测试安全路由时都需要登录吗? I've tried passing global vars around after i get the initial token but passing vars i'm finding extremely counter intuitive.我尝试在获得初始令牌后传递全局变量,但传递变量我发现非常反直觉。 Passing variables in a before() call presents me same issue as passing / accessing global vars inside nested promises.在 before() 调用中传递变量给我带来了与在嵌套承诺中传递/访问全局变量相同的问题。
describe('Users', function(done) {
var testToken = 'my-test-token'
it('logs in', function(done) { // <= Pass in done callback
var rT = 'tttttt'
chai.request(urlroot)
.post('/login')
.type('form')
.send({ email: 'test_user_1@this.com', password: '9999' })
.end(function(err, res) {
expect(res).to.have.status(200);
expect(res.body.token).to.be.a('string');
done()
});
});
it('gets all users', function(done) { // <= Pass in done callback
// console.log(urlroot + '/users');
chai.request(urlroot)
.post('/login')
.type('form')
.send({ email: 'test_user_1@this.com', password: '9999' })
.end(function(err, res) {
chai.request(urlapi)
.get('/users?secret_token='+res.body.token)
.end(function(err, res){
console.log('data', res.body);
// expect(res.body).to.be.json()
})
});
});
});
What I do is use before()
method to call my authenticate service to get the token in the same way that the aplication would, and store into a variable.我所做的是使用before()
方法调用我的身份验证服务,以与应用程序相同的方式获取令牌,并将其存储到变量中。
Something like:就像是:
var token = "";
before(async () => {
//Get token
token = "Bearer " + await getToken();
});
Then, in every test you want to use the credentials use .set()
然后,在您想要使用凭据的每个测试中,使用.set()
it('...', function (done) {
chai
.request(url)
.set("Authorization", token) //Call .set() before .get()
.get("/users")
//...
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.