Search code examples
javascriptnode.jsexpressmocha.jssupertest

With Supertest, can I create an alternative request with some headers set by default?


I am using Supertest with Mocha to test an API developed with Node JS.

And I want to do a lót of different tests on the API. With almost all of them I have to set Authorization and Content-Type headers again (because the API requires them for this test).

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: "[email protected]"
    })
    .expect('Content-Type', /json/)
    .expect(500)
    .expect(anErrorCode('50086'))
    .end(done);
});

Can I create an alternative request with those headers set by default?


Solution

  • If i remember correctly in superagent one can pass a hash to set

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

    let me know if it doesnt work with supertest.