mardi 18 octobre 2016

Test request mongoose promise

I'm going crazy, I try to test this route with mocha and supertest but i'm blocked. I log worker._id but it is empty, request pending with : Appointments appointments should save a user and not save the same:

Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.

Mongoose log print this : Mongoose: users.find({ department: 95 }, { fields: undefined })
Mongoose: users.find({ department: 95 }, { fields: undefined })

--And Stop

This is my code :

appointments.controller.js

module.exports = function(app, ObjectId, nodemailer, User) {
app.route('/appointments')
.post(function(req,res){
    // console.log('Appoint',req.body.start);
    if(req.body.start != undefined){
        date = moment(req.body.start).locale("fr");
        min = moment(date).subtract(3, 'hours');
        max = moment(date).add(3, 'hours');
    }

    User.find({'department': req.body.department}, function(err, workers){
        return workers._id;
    }).then(function(allWorkers){
        //Sort by Available Worker
        return Appointments.defineDispWorker(allWorkers, date);
    }).then(function(dispoWorkers){

        if(dispoWorkers.length > 0) {

            //Save appointment with the good available Worker
            // saveAppointment(res,req,dispoWorkers);

            function saveAppointment(res,req,dispoWorkers){
                var newAppointment = new Appointments();
                newAppointment.title = req.body.title;
                newAppointment.start = date;
                newAppointment.worker = dispoWorkers[0]._id;
                newAppointment.department = req.body.department;

                var promise = newAppointment.save();

                promise.then(appointmentComplete).catch(appointmentFailure);

                function appointmentComplete(resolve) {
                    res.status(200);
                }

                function appointmentFailure(reject) {
                    res.status(500);
                }
            }

        } else {
            res.status(409);
        }
    })
    .catch(function(error) {
        res.status(500).end();
    });
})

appointments.model.js

AppointmentsSchema.statics.defineDispWorker = function defineDispWorker (allWorkers, date) {
var deferred = Q.defer();

function sortWorkers(worker){
    return mongoose.model('Appointments').find({worker: worker._id, start: date});
};

Q.all(_.map(allWorkers, sortWorkers)).done(function (val) {

    deferred.resolve(checkWorkersBusy(val, allWorkers));

});

return deferred.promise;
}

Test.js

request(app)
        .post("/appointments")
        .send(appointments)
        .then(function (res) {
          console.log(res);
          done();
        });

Aucun commentaire:

Enregistrer un commentaire