如何使用mocha和supertest测试带有头参数的快速休息api?

时间:2015-07-16 20:48:07

标签: node.js rest mocha supertest

我必须测试我的休息api。某些路由需要用户身份验证令牌的http请求标头中的值。

我在纯javascript代码中分离了我有趣的业务逻辑,但我找不到一种方法来测试在http请求的标头中需要令牌的路由。

欢迎使用mocha和/或supertest的其他替代品。

1 个答案:

答案 0 :(得分:11)

使用supertest,您可以使用set关键字设置标头参数:

api.get('/aroute/')
...
.set('headerParameterName', value)
...

以下是使用supertest测试带有令牌授权的快速服务器API的示例:

app.js

var express = require('express');
var app = express();
var jwt = require('jsonwebtoken');
var expressJwt = require('express-jwt');

var secret = 'my-secret';

app.get('/get-token', function(req, res) {
  var token = jwt.sign({foo: 'bar'}, secret);
  res.send({token: token});
});

app.post(
  '/test',
  expressJwt({
    secret: secret
  }),
  function(req, res) {
    res.send({message: 'You could use the route!'});
  }
);

app.use(function(err, req, res, next) {
  res.status(err.status || 500).send({error: err.message});
});

app.listen(4040, function() {
  console.log('server up and running at 4040 port');
});

module.exports = app;

test.js

var request = require('supertest');
var app = require('./app.js');

describe('Test Route with Token', function() {
  var token = '';

  before(function(done) {
    request(app)
      .get('/get-token')
      .end(function(err, res) {
        var result = JSON.parse(res.text);
        token = result.token;
        done();
      });
  });

  it('should not be able to consume the route /test since no token was sent', function(done) {
    request(app)
      .post('/test')
      .expect(401, done);
  });


  it('should be able to consume the route /test since token valid was sent', function(done) {
    request(app)
      .post('/test')
      .set('Authorization', 'Bearer ' + token)
      .expect(200, done);
  });
});