Mocha 测试服务器提供的经过身份验证的 API

Mocha Testing authenticated APIs provided by a server

我的API登录后就可以使用了。例如,/api/sales需要如下代码的验证。 (我正在使用 Node.js 和 Express.js)

app.all('/api/*', userController.requiresLogin);
app.route('/api/sales')
    .get(common.readAll(Sale, 'name'))
    .post(common.create(Sale));

userController.requiresLogin函数是:

exports.requiresLogin = function(req, res, next) {
    console.log('Check login...');

    if(!req.user) return res.status(401).send();
    else next();
};

要登录,我使用 passport.js

exports.login = passport.authenticate('local', {
    successRedirect: '/',
    failureRedirect: '/login',
    failureFlash: false
});

当我 运行 我的服务器并在我的浏览器上测试这个 API 时,它有效。

为了自动测试这个 API,我使用 Supertest 构建了我的 Mocha 测试代码。

    var request = require('supertest'),
        should = require('should'),
        utils = require('./../utils'),
        mongoose = require('mongoose');

    var Sale = mongoose.model('Sale'),
        User = mongoose.model('User');

    var user;

    describe('Controller Testing:', function() {
        describe('Sale Controller Testing:', function() {
            var agent = request.agent();

            beforeEach(function(done) {
                user = new User({
                    username:'defaultUser@test.com',
                    password: 1234,
                    userId: 'default user'
                });
                user.save();

                request(app).post('/login')
                    .send( {username: 'defaultUser@test.com', password: '1234'} )
                    .end(function(err, res) {
                        should.not.exist(err);
                        agent.saveCookies(res);
                        done();
                    });
            });

            afterEach(function() {
                User.remove({}, function(){});
                Sale.remove({}, function(){});
            }

            it('create a sale', function(done) {
                var sale = {
                    name: 'New Sale',
                    orders: [order1]
                };

                var req = request(app).post('/api/sales')
                    .send(sale)
                    .expect('Content-Type', /json/)
                    .expect(200);
                agent.attachCookies(req);

                req.end(function(err, res) {
                    console.log(res.statusCode);

                    res.body.name.should.equal('New Sale');
                    done();
                });
            });
    }

这个测试保持失败。测试 'create a sale' 无法识别用户已登录,即使我保存并附加了相应的 cookie。

检查supertest npm page,并将您的测试脚本修改为

   var request = require('supertest'),
    should = require('should'),
    utils = require('./../utils'),
    mongoose = require('mongoose');

var Sale = mongoose.model('Sale'),
    User = mongoose.model('User');

var user;

describe('Controller Testing:', function() {
    describe('Sale Controller Testing:', function() {
        var agent = request.agent(app); // revised

        beforeEach(function(done) {
            user = new User({
                username:'defaultUser@test.com',
                password: 1234,
                userId: 'default user'
            });
            user.save();

            agent.post('/login') // revised
                .send( {username: 'defaultUser@test.com', password: '1234'} )
                .expect("set-cookie", "check correct cookie here") // appended
                .end(function(err, res) {
                    should.not.exist(err);
                    //agent.saveCookies(res);
                    // or write some code to check your cookie here
                    done();
                });
        });

        afterEach(function() {
            User.remove({}, function(){});
            Sale.remove({}, function(){});
        }

        it('create a sale', function(done) {
            var sale = {
                name: 'New Sale',
                orders: [order1]
            };

            var req = agent.post('/api/sales') // revised
                .send(sale)
                .expect('Content-Type', /json/)
                .expect(200);
            //agent.attachCookies(req);

            req.end(function(err, res) {
                console.log(res.statusCode);

                res.body.name.should.equal('New Sale');
                done();
            });
        });
}

我没有在你的测试脚本中看到 app 来自哪里,假设你正确地得到它并应用了 cookieParser 中间件。

我认为您的测试脚本中的问题是在附加 cookie 之前发送的请求。也许你也可以试试

var req = aggent.attachCookies(request(app));
req.post('/api/sales')
     .send(sale)
     .expect('Content-Type', /json/)
     .expect(200);
     //agent.attachCookies(req);