存根使用 Sinon 进行回调的方法

Mil*_*deh 5 javascript mocha.js node.js sinon chai

我想知道我的方法是否正确,以及类似情况的最佳做法是什么。

设想

我正在尝试使用 Sinon.js 在我的 authController 中存根一个函数调用,它接受两个参数并在回调函数中处理结果以将其传递给 Next() 回调。类似的东西:

  // requestController.js
  module.exports = function(req, res, next) {
     authController.handle(req, res, function(apiMethod) {

        if (apiMethod !== undefined || apiMethod !== null) {
             apiMethod(next);
        } else {
             next();
        }
     });
 };
Run Code Online (Sandbox Code Playgroud)

上面的方法在我的 requestController 中被调用,它处理所有请求并需要 authController 来检查身份验证。

问题是我如何使用 sinon 来存根或模拟的行为authController并返回一个假的,apiMethod但其余的代码继续并调用next().

预先感谢您的建议。

Ale*_*gin 2

仍然有一个错误。对于单元测试,您的代码应如下所示:

 module.exports = function(req, res, next) {
     apiMethod = function() {
        //your code goes here
     }

     authController.handle(req, res, apiMethod);
 };
Run Code Online (Sandbox Code Playgroud)

包裹起来的函数apiMethod是多余的