使用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();
});
});
});
});
您可以只将用户添加到测试套件中。您可以通过在服务器端测试脚本中填充这些用户来实现这一点:
类似于:
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/Jastsmine数据库中有合适的用户和正确的角色即可。
假设您有这样一个服务器端方法:
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
上下文来存根this.userId
。
所有定义的流星方法都可以在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
您在测试什么?为什么需要用户登录?我拥有的大多数方法都需要一个用户对象,我将用户对象传递到其中。这允许我在没有实际登录的情况下从测试中调用。所以在实际运行代码时,我会通过…
var r = myMethod(Meteor.user());
但当我从测试中跑出来时,我会打电话给。。。
it('should be truthy', function () {
var r = myMethod({_id: '1', username: 'testUser', ...});
expect(r).toBeTruthy();
});
我认为Meteor.server.method_handlers["nameOfMyMethod"]
允许您调用/应用Meteor方法,并至少在当前版本(1.3.3)中提供this
作为第一个参数
this.userId = userId;
Meteor.server.method_handlers["cart/addToCart"].apply(this, arguments);