lundi 5 juin 2017

How to test nested asynchronous calls in Javascript?

I would like to unit-test the function getAuthorizedUsers from the following module. The core functionality that I need to test is in the callback function of DB.getUsers. I could not find a way to mimic the callback of DB.getUsers.

(function () {
    const DB = require('./DB');

    function getAuthorizedUsers(req, res, callback) {
        DB.getUsers(req.db, req.userId, function(err, users) {
            users.push({id: 0});
            req.users = users;
            callback(req, res);
        });
    }

    module.exports = {
        getAuthorizedUsers: getAuthorizedUsers
    };
})();

Here is what I have so far:

(function () {
    "use strict";

    var chai = require("chai");
    var User = require("./User");

    suite("API", function () {
        suite("getAuthorizedUsers", function() {
            var req = {
                db: {},
                userId: '',
            };
            var res = {};
            test("adds admin to list of authorized users", function() {
                User.getAuthorizedUsers(req, res, function(req, res) {
                    //assert that req contains the correct list of authorized users
                });
            });
        });
    });
}());

I have changed names, and logic of code for simplification. So, forgive me if code does not follow the best practices or does not make sense.

Aucun commentaire:

Enregistrer un commentaire