How to test a recursively called function in NodeJS?

http://stackoverflow.com/questions/34404766/how-to-test-a-recursively-called-function-in-nodejs/36625016#36625016

by Ben Smith

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/sinon.js/1.15.4/sinon.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine.css">
<script src="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine.js"></script>
<script src="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine-html.js"></script>
<title>Jasmine Spec Runner</title>

JavaScript

// A module which has methods you want to stub
User = (function() {

  // Constructor
  function User() {}

  User.prototype.findOneAsync = function(object) {
    return {};
  };

  return User;

})();

// Stub the method behaviour using Sinon javascript framework
var user = new User();
var userStub = sinon.stub(user, 'findOneAsync');
userStub.onFirstCall().returns(null);
userStub.onSecondCall().returns({});

// A method which is dependent on the module
// Keep checking if there is a user, if there is let execution continue
checkIfUserExists = function(_user) {

  var user = _user.findOneAsync({});

  // if there is no user delay one minute and check again
  if(user === null){
  	console.log('no user');
    // Use a simple timer for this example!
    setTimeout(function() {}, 100);
    return checkIfUserExists(_user);
  } else {
  console.log('user found');
    // otherwise, if there a user, let the execution move on
    return true;
  }
};

// Assert method behaviour using a Jasmin test
describe("User test suite", function() {
  it("Test that recursion works", function() {   
    expect(checkIfUserExists(user)).toBe(true);
  });
});

// load jasmine htmlReporter
(function() {
  var env = jasmine.getEnv();
  env.addReporter(new jasmine.HtmlReporter());
  env.execute();
}());