[英]Supertest, test secure REST API
I am writing an integration test for a REST API protected by a jwt
.我正在为受jwt
保护的 REST API 编写集成测试。 One API operation POST /user/token
is returning a jwt
given a username
and a password
and this token is then used for a list of operations such as:一个 API 操作 POST /user/token
返回一个给定username
和password
的jwt
,然后这个令牌用于一系列操作,例如:
GET /user/:id
Where the route is using jwt({secret: secret.secretToken})
, so the token is included into the HTTP header Authorization
.其中路由使用jwt({secret: secret.secretToken})
,因此令牌包含在 HTTP 标头Authorization
。
When testing with supertest, I can have nested testing but I want to first get the token, then use this token for testing other operations.使用 supertest 进行测试时,我可以进行嵌套测试,但我想先获取令牌,然后使用此令牌来测试其他操作。
POST /user/token => 12345
GET /user/:id, `Authorization Bearer 12345`
GET /user/:foo, `Authorization Bearer 12345`
How to avoid generating a new token for every operation testing (see below) but use only a single one generate by POST /user/token.如何避免为每个操作测试生成一个新令牌(见下文),但只使用一个由 POST /user/token 生成的令牌。
it('should get a valid token for user: user1', function(done) {
request(url)
.post('/user/token')
.send({ _id: user1._id, password: user1.password })
.expect(200) // created
.end(function(err, res) {
// test operation GET /user/:id
You want to perform single POST to /user/token
and then use the token received in every test case?您想对/user/token
执行单个 POST,然后使用在每个测试用例中收到的令牌? If so, then use the before
hook of the test framework you are using (Mocha?) and store the token to a variable, eg如果是这样,那么使用您正在使用的测试框架的before
钩子(Mocha?)并将令牌存储到变量中,例如
describe('My API tests', function() {
var token = null;
before(function(done) {
request(url)
.post('/user/token')
.send({ _id: user1._id, password: user1.password })
.end(function(err, res) {
token = res.body.token; // Or something
done();
});
});
it('should get a valid token for user: user1', function(done) {
request('/get/user')
.set('Authorization', 'Bearer ' + token)
.expect(200, done);
});
});
Need to set Authorization as 'Bearer ' + token需要将Authorization设置为 'Bearer' + token
var token = null;
before(function(done) {
request(url)
.post('/user/token')
.send({ _id: user1._id, password: user1.password })
.end(function(err, res) {
token = res.body.token; // Or something
done();
});
});
it('should get a valid token for user: user1', function(done) {
request('/get/user')
.set('Authorization', 'Bearer ' + token)
.expect(200, done);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.