Meteor/Jasmine/Velocity:如何测试需要登录用户的服务器方法?

Pet*_*rov 8 meteor meteor-velocity meteor-jasmine

使用velocity/jasmine,我有点不知道应该如何测试服务器端方法,要求当前登录的用户.有没有办法让Meteor认为用户是通过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();

            });
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

Tho*_*den 5

您可以做的是将用户添加到您的测试套件中.您可以通过在服务器端测试脚本中填充这些用户来完成此操作:

就像是:

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

然后,一个好的策略可能是beforeAll在您的测试中使用登录(这是客户端):

Jasmine.onTest(function() {
  beforeAll(function(done) {
    Meteor.loginWithPassword('test-user','pwd', done);
  }
}
Run Code Online (Sandbox Code Playgroud)

这是假设您的测试尚未登录.你可以通过检查Meteor.user()和正确登出afterAll等来使这更加花哨.请注意如何轻松地将done回调传递给许多Accounts函数.

基本上,您不必模拟用户.只需确保您拥有Velocity/Jasmine数据库中提供的具有正确角色的正确用户.


Sha*_*Lim 5

假设你有一个像这样的服务器端方法:

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';
    }
});
Run Code Online (Sandbox Code Playgroud)

在执行方法之前,您不需要创建Meteor.loginWithPassword.您所要做的就是this.userId通过更改this方法函数调用的上下文来存根.

Meteor.methodMap对象上可以使用所有已定义的流星方法.所以只需使用不同的this上下文调用该函数

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');
    });

});
Run Code Online (Sandbox Code Playgroud)

编辑:此解决方案仅在Meteor <= 1.0.x上测试

  • Meteor.methodMap对我来说是未定义的(Meteor版本1.2.0.2)? (4认同)