Supertest,我可以创build一个替代的请求与默认设置一些标头?

我正在用Mocha的Supertest来testing用Node JS开发的API。

我想在API上做很多不同的testing。 几乎所有的人都必须重新设置Authorization和Content-Type头(因为API需要这个testing)。

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); }); 

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

Solutions Collecting From Web of "Supertest,我可以创build一个替代的请求与默认设置一些标头?"

如果我没有记错的话,可以通过散列来设置

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

让我知道,如果它不适用于超级。

你可以使用一个通用的例程来构build你的“默认”头文件作为对象,并将它们传递给请求:

 //# 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 }) }) 

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

您可以如下应用软件包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