meteormeteor-velocitymeteor-jasmine

Meteor / Jasmine / Velocity : how to test a server method requiring logged in user?


Using velocity/jasmine, I'm a bit stuck on how I should test a server-side method requiring that there be a currently logged-in user. Is there a way to make Meteor think a user is logged in via stub/fake ?

myServerSideModel.doThisServerSideThing = function(){
    var user = Meteor.user();
    if(!user) throw new Meteor.Error('403', 'not-autorized');
}

Jasmine.onTest(function () {
    describe("doThisServerSideThing", function(){
        it('should only work if user is logged in', function(){
            // this only works on the client :(
            Meteor.loginWithPassword('user','pwd', function(err){
                expect(err).toBeUndefined();

            });
        });
    });
});

Solution

  • What you could do is add users just to your test suite. You could do this by populating these users in a the server-side test script:

    Something like:

    Jasmine.onTest(function () {
      Meteor.startup(function() {
        if (!Meteor.users.findOne({username:'test-user'})) {
           Accounts.createUser
              username: 'test-user'
      ... etc
    

    Then, a good strategy could be to use the beforeAll in your test to login (this is client side):

    Jasmine.onTest(function() {
      beforeAll(function(done) {
        Meteor.loginWithPassword('test-user','pwd', done);
      }
    }
    

    This is assuming your test isn't logged in yet. You can make this more fancy by checking for Meteor.user() and properly logging out in an afterAll, etc. Note how you can handily pass the done callback to many of the Accounts functions.

    Essentially, you don't have to mock a user. Just make sure you have the right users, with the correct roles, available in the Velocity/Jasmine DB.