我想從下面的模塊中對函數getAuthorizedUsers進行單元測試。我需要測試的核心功能是在DB.getUsers的回調函數中。我無法找到模仿DB.getUsers回調的方法。如何在Nodejs中測試嵌套的異步調用?
(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
};
})();
這是我到目前爲止有:
(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
});
});
});
});
}());
我已經改了個名字,而爲了簡化代碼邏輯。所以,如果代碼不遵循最佳實踐或者沒有意義,請原諒我。
編輯:你有什麼建議如何存根「DB.getUsers」?
https://mochajs.org/#asynchronous-code –