Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Supertest, test secure REST API

Tags:

I am writing an integration test for a REST API protected by a jwt. 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:

GET /user/:id

Where the route is using jwt({secret: secret.secretToken}), so the token is included into the HTTP header 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.

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.

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
like image 208
JohnJohnGa Avatar asked Oct 19 '14 18:10

JohnJohnGa


People also ask

What is SuperTest in API testing?

SuperTest is a Node. js library that helps developers test APIs. It extends another library called superagent, a JavaScript HTTP client for Node. js and the browser. Developers can use SuperTest as a standalone library or with JavaScript testing frameworks like Mocha or Jest.

What is the difference between jest and SuperTest?

Jest provides us matchers like toBe and toContain that can be used to test that the responses have an exact value or contain a certain value respectively. Supertest includes the expect method that allows us test the statuscode of the response and the type of the response.


1 Answers

You want to perform single POST to /user/token and then use the token received in every test case? If so, then use the before hook of the test framework you are using (Mocha?) and store the token to a variable, e.g.

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);
  });
});
like image 195
vesse Avatar answered Sep 20 '22 10:09

vesse