1

I have a piece of middleware that checks a users authentication based on a passed parameter. The middleware uses a model that implements promises to find and return the user to be set into the request params.

The problem is, when running tests, if an assertion fails the test times out, presumably because the exception thrown by the failing assertion is not able to be handled by Mocha.

I'm doing the assertions inside of the next() function - When testing that the key was not provided, it works correctly, I assume because it's not being run in the context of the promise.

# Authenticator
var Authentication = function(model) {
    this.model = model;
};

Authentication.prototype.resolve = function(customerKey) {
    return this.model.authenticate(customerKey);
};

module.exports = function(model) {
    return function(req, res, next) {
        if (!req.query.hasOwnProperty('customerKey')) {
            throw new Error('There was no auth key provided');
        }

        var auth = new Authentication(model);

        auth.resolve(req.query.customerKey)
        .then(function(customer) {
            if (!customer) {
                throw new Error('There was no customer found with the supplied auth key');
            }

            req.params.auth = customer;
        })
        .done(next, next);
    };
};

# Test
var should          = require('chai').should(),
    authentication  = require('src/api/middleware/authentication'),
    model           = require('src/models/customer'),
    auth            = authentication(model);

describe('middleware/authentication', function() {
    it('should set the user to the request if the customerKey is valid', function(done) {
        var request = {
            query: {
                customerKey: 'thisIsValid'
            },
            params: {}
        };

        var response = function() {
            // This is a no-op
        };

        var next = function(response) {
            response.should.be.instanceOf(String); // If this assertion fails, the test times out and doesn't work
            response.should.have.property('name');
            response.name.should.be.a('string');

            done();
        };

        // Actually calls the auth 
        auth(request, response, next);
    });
});
nullfox
  • 597
  • 1
  • 4
  • 16
  • What flavour of Promises is your customer model implementing? Why does your `.done` call take two arguments instead of just one? Did you mean to call `.then` instead of `.done`? In your `.then` call, you should probably return a rejected promise instead of throwing an exception. Depending on the flavour of Promises being used, you may also have to return something in the success case in your `.then` handler. – Ates Goral Aug 26 '14 at 03:46

0 Answers0