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

时间:2016-07-28 20:22:08

标签: node.js rest testing 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?

1 个答案:

答案 0 :(得分:0)

You need to tell Mocha that your before function is asynchronous, by accepting a done parameter and calling it when logging in has completed, e.g.

before(function(done){
        agent.post('/login').send({ user.username, user.key })
            .end(function(err, res) {
                // I assume you're logged in here...
                done();
            }
    }

Of course, you'll also want to add the required error handling etc. You'll probably want to create a new describe block for each user too, otherwise all of the login calls will run before any user tests happen, e.g.

users.forEach(function(user){
    describe("user X tests", function() { // <-- NEW
    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
            }
    }
    }); // <- NEW
}