Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stub a method that does a callback using Sinon

I would like to know if my approach is correct, and what is the best practice for similar situation.

Scenario

I am trying to use Sinon.js to stub a function call in my authController, which takes two arguments and process the result in a Callback function to pass it to Next() callback. something similar to this:

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

        if (apiMethod !== undefined || apiMethod !== null) {
             apiMethod(next);
        } else {
             next();
        }
     });
 };

the above method is being called inside my requestController which handles all the requests and needed authController to check the authentication.

The question is how can I use sinon to stub or mock the behavior of authController and return a fake apiMethod but the rest of code continues and calls the next().

Thanks in advance for your recommendations.

like image 424
Milad Rezazadeh Avatar asked Oct 30 '22 15:10

Milad Rezazadeh


1 Answers

There is still an error. For unit tests your code should look like this:

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

     authController.handle(req, res, apiMethod);
 };

The function wrapped around apiMethod is redundant

like image 75
Alexander Elgin Avatar answered Nov 12 '22 19:11

Alexander Elgin