8

使用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();

            });
        });
    });
});
4

4 回答 4

5

您可以做的只是将用户添加到您的测试套件中。您可以通过在服务器端测试脚本中填充这些用户来做到这一点:

就像是:

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

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

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

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

本质上,您不必模拟用户。只要确保您在 Velocity/Jasmine DB 中拥有正确的用户和正确的角色即可。

于 2015-03-03T16:55:14.313 回答
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';
    }
});

在执行该方法之前,您不需要创建 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');
    });

});

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

于 2015-03-08T06:42:26.897 回答
1

您在测试什么,为什么需要用户登录?我拥有的大多数方法都需要一个用户对象,我将用户对象传递到其中。这允许我在没有实际登录的情况下从测试中调用。所以在代码的实际运行中我会通过......

var r = myMethod(Meteor.user());

但是当从测试中运行时,我会打电话给......

it('should be truthy', function () {
  var r = myMethod({_id: '1', username: 'testUser', ...});
  expect(r).toBeTruthy();
});
于 2015-03-02T03:50:27.380 回答
1

我认为这Meteor.server.method_handlers["nameOfMyMethod"]允许您调用/应用 Meteor 方法并this至少在当前版本(1.3.3)中作为第一个参数提供

this.userId = userId;
Meteor.server.method_handlers["cart/addToCart"].apply(this, arguments);
于 2016-06-15T04:28:27.913 回答