jeudi 28 juillet 2016

Dynamically testing authentication RESTful API (NodeJS, Mocha, SuperAgent)

Goal:

I am trying to test my authentication RESTful API. The tools i am using are NodeJS with the modules: Mocha, Supertest(.agent) and chai(.assert).

What i tried:

var users = [ new User("admin", "secretPass"), new User("guest", "Pass")];
describe('request some protected data', function(){
    users.forEach(function(user){
        before(function(){
            agent.post('/login').send({ user.username, user.key })
                .end(function(err, res) {

                }
        }

        it('get data', function(done){
            agent.get('/data').send({ user.username, user.key })
                .end(function(err, res) {
                    // assertions on data
                }
        }
    }
}

The problem:

Using something similar to the snippet above results in multiple before functions being executed at once and after that all the tests(it). So agent will always be logged in as the last user in users.

I tried to replace before with beforeEach and place it above users.forEach, but then user will be out of scope.

Can anyone provide me with a small snippet of code that will explain a suitable solution for my problem?

Aucun commentaire:

Enregistrer un commentaire