Search code examples
javascriptmocha.jssupertest

MochaJS - Reuse block in other files


Currently I'm using SuperTest to test an API and to each request I need to get the access token from admin user, so I created this request (works fine):

authenticate.js

const request = require('supertest');

var storeAccessToken;

describe ('POST /Authenticate', function() {
    it ('Should return access token', function(done) {
        request('http://myendpoint.com')
        .post('/TokenAuth/Authenticate')
        .send({
            "username": "admin",
            "password": "admin"})
        .end(function(err, res) {
            if (err) return done(err);
            storeAccessToken = res.body.result.accessToken;
            done();
        });
    });
}); 

Now I have the access token stored (variable storeAccessToken), I need to call this same code in the before() of another file.

getKpiRequest.js

const request = require('supertest');

var storeAccessToken;

describe ('GET /Kpi/Availables', function() {

    before(function (done){
        request('http://myendpoint.com')
        .post('/TokenAuth/Authenticate')
        .send({
            "username": "admin",
            "password": "admin"})
        .end(function(err, res) {
            if (err) return done(err);
            storeAccessToken = res.body.result.accessToken;
            assert.equal(res.status, 200);
            done();
        });
    });
});

How can avoid to repeat the code in getKpiRequest.js file?


Solution

  • You can define authentication function in another file, then import it into test files

    // common.js
    function authenticate() {
    
      return request('http://myendpoint.com')
            .post('/TokenAuth/Authenticate')
            .send({
                "username": "admin",
                "password": "admin"})
            .then((res) => {
                assert.equal(res.status, 200);
                return res.body.result.accessToken;
            });
    }
    
    module.exports = {
      authenticate
    }
    
    // authenticate.js 
    
    const request = require('supertest');
    const authenticate = require('./common').authenticate;
    
    var storeAccessToken; 
    
    describe ('POST /Authenticate', function() {
        it ('Should return access token', function(done) {
            authenticate().then((token) => {
              storeAccessToken = token;
              done();
            }).catch(done);
        });
    }); 
    
    // getKpiRequest.js
    
    const request = require('supertest');
    const authenticate = require('./common').authenticate;
    
    var storeAccessToken;
    
    describe ('GET /Kpi/Availables', function() {
    
        before(function (done){
            authenticate()
            .then((token) {
                storeAccessToken = token;
                done();
            }).catch(done);
        });
    });
    

    Keep the function general so you can reuse it