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

前端 未结 4 1723
萌比男神i
萌比男神i 2021-02-15 17:50

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

4条回答
  •  遥遥无期
    2021-02-15 18:43

    Lets say you have a server side method like this:

    Meteor.methods({
        serverMethod: function(){
            // check if user logged in
            if(!this.userId) throw new Meteor.Error('not-authenticated', 'You must be logged in to do this!')
    
           // more stuff if user is logged in... 
           // ....
           return 'some result';
        }
    });
    

    You do not need to make a Meteor.loginWithPassword before executing the method. All you got to do is stub the this.userId by changing the this context of the method function call.

    All defined meteor methods are available on the Meteor.methodMap object. So just call the function with a different this context

    describe('Method: serverMethod', function(){
        it('should error if not authenticated', function(){
             var thisContext = {userId: null};
             expect(Meteor.methodMap.serverMethod.call(thisContext).toThrow();
        });
    
        it('should return a result if authenticated', function(){
             var thisContext = {userId: 1};
             var result = Meteor.methodMap.serverMethod.call(thisContext);
             expect(result).toEqual('some result');
        });
    
    });
    

    EDIT: This solution was only tested on Meteor <= 1.0.x

提交回复
热议问题