Search code examples
node.jsmocha.jsfacebook-authenticationeveryauthsuperagent

Mocking everyauth login in a mocha test - nodejs


I am new to mocha and am trying to get familiar with writing tests in mocha. I have a scenario where I am currently using everyauth to authenticate users using facebook authentication. Thus, I may have a request to an endpoint users/profile which is shown below:

router.route('/profile')
  .get(function(req, res) {
    if(req.session.auth) {
      res.json({
        user: req.user.toObject({getters: true})
      });
    } else {
      res.status(HttpStatus.UNAUTHORIZED);
      res.json({
        message: 'You need to be logged in to view this information'
      });
    }
  });

If I wanted to test this endpoint using mocha and superagent, how would I go about doing so? How will I be able to simulate a login with everyauth using the mocha framework.

I currently have a test that is shown below:

  it('should return user information on being logged in', function(done) {
    superagent.get(url + '/users/profile').end(function(err, res) {
      expect(res.status).to.equal(200);
      expect(res.body).to.eql({
          users: // some user object
      });
      done();
    });
  });

However, unless I am able to simulate the login, I cannot test whether the correct data is being returned via the call to the endpoint.


Solution

  • Certainly one solution to this would be to mock the authentication modules for testing purposes with a mocking/stubbing framework such as the very popular Sinon stubs. Sinon lets you "override" a function so that instead of that function running, it returns whatever you want it to return.

    Without being familiar with everyauth, you would want something like this:

    sinon.stub(everyauth, "authenticateUser").yields(null, {
        user: {
            firstName: 'John',
            // etc.
        }
    });
    

    Where everyauth is the main object, authenticateUser is the method you want to stub, and yields should return exactly what "authenticateUser" would normally return, so this could return the Facebook User object that is normally returned so you can continue to test the functionality of the app.