使用Supertest,我可以创建一个备用请求,默认设置一些标头吗?

时间:2014-05-18 18:51:03

标签: javascript node.js express mocha supertest

我正在使用Supertest与Mocha一起测试使用Node JS开发的API。

我想对API进行不同的测试。几乎所有这些都必须再次设置Authorization和Content-Type标头(因为API要求它们进行此测试)。

it('Creation without an email address should fail and return error code 50040', function(done) {
  request
    .post('/mpl/entities')
    .set('Authorization', 'Token 1234567890') //set header for this test
    .set('Content-Type',  'application/json') //set header for this test
    .send({
      firstname: "test"
    })
    .expect('Content-Type', /json/)
    .expect(500)
    .expect(anErrorCode('50040'))
    .end(done);
});

it('Creation with a duplicate email address should fail and return error code 50086', function(done) {
  request
    .post('/mpl/entities')
    .set('Authorization', 'Token 1234567890') //<-- again
    .set('Content-Type',  'application/json') //<-- again, I'm getting tired
    .send({
      email: "a@b.nl"
    })
    .expect('Content-Type', /json/)
    .expect(500)
    .expect(anErrorCode('50086'))
    .end(done);
});

我可以使用默认设置的标头创建替代请求吗?

4 个答案:

答案 0 :(得分:28)

如果我在superagent中记得正确,可以传递哈希来设置

.set({key:value,key2:value2})

让我知道它是否与supertest无关。

答案 1 :(得分:10)

您可以使用公共例程将“默认”标题构建为对象并将其传递给请求:

//# file:config.js

var config = { 
  authorization: { "Authorization":"authvalue" }
}

// Content-Type left out because supertest will use Content-Type json when you use the appropriate method

module.exports = config;

现在你的test.js:

//# file:test.js

var request = require("supertest");
var config = require("./config");

request = request(config.baseUrl)
var commonHeaders = { "authorization":"TokenValueASDF" };

describe("testing", function() {
  it.should('present authorization header to server', function(done) {
    request.get('/someurl')
      .set(commonHeaders)
      .set({"X-TestSpecificHeader":"Value"})
      .expect(200,done) //if not authorized you'd get 401
  })

})

此外,如果您需要让您的应用在运行时获取该令牌值(最有可能),请参阅本文以了解使用为测试生成的请求令牌值: https://jaketrent.com/post/authenticated-supertest-tests/

答案 2 :(得分:4)

您可以使用库superagent-defaults,如下所示:

安装

npm install --save-dev supertest superagent-defaults

使用

var defaults = require('superagent-defaults');
var supertest = require('supertest');

var request = defaults(supertest(app)); // or url

// set the default headers
request.set(commonHeaders);

// use as usually

版本

  • supertest v3.0.0
  • superagent-defaults v0.1.14

答案 3 :(得分:0)

我过去经常做的事情是

首先我创建一个配置文件来存储默认标题,

配置文件:

//# file: defaults.js
var defaults = { 
  l5dDtab: "SomeValue",
  xSignature: true,
  ... more headers here
}
module.exports = defaults;

然后,在我使用 supertest 的每个测试文件上,我都这样做:

var defaults = require('./defaults.js');
var supertest = require('supertest');

var host = 'http://localhost:8080';
var request = supertest.agent(host)
            .set("l5d-dtab", defaults.l5dDtab)
            .set("X-Signature", defaults.xSignature);
var response = request.get("SomePath").set("AnotherLocalHeader", "Value");