2017-05-09 26 views
1

我正在学习流星,基本的“Todo教程”来自官方网站。我遇到了“测试”步骤的问题。 我有一个方法的基本测试,它看起来像这样:“Meteor.userId只能在方法调用中调用”流星方法测试

if (Meteor.isServer) { 
    describe('Tasks',() => { 
     describe('methods',() => { 
      const userId = Random.id(); 
      let taskId; 

      beforeEach(() => { 
       Tasks.remove({}); 
       taskId = Tasks.insert({ 
        text: 'test task', 
        createdAt: new Date(), 
        owner: userId, 
        username: 'tmeasday', 
       }); 
      }); 

      it('can delete owned task',() => { 
       const deleteTask = Meteor.server.method_handlers['tasks.remove']; 

       const invocation = { userId }; 
       deleteTask.apply(invocation, [taskId]); 
       assert.equal(Tasks.find().count(), 0); 
      }); 
     }); 
    }); 
} 

此测试失败,出现错误:

Error: Meteor.userId can only be invoked in method calls. Use this.userId in publish functions. 
    at AccountsServer.userId (packages/accounts-base/accounts_server.js:82:13) 
    at Object.Meteor.userId (packages/accounts-base/accounts_common.js:257:19) 
    at Object.Meteor.methods.tasks.remove (imports/api/tasks.js:37:35) 
    at Test.<anonymous> (imports/api/tasks.tests.js:27:28) 
    at run (packages/practicalmeteor:mocha-core/server.js:34:29) 
    at Context.wrappedFunction (packages/practicalmeteor:mocha-core/server.js:63:33) 

IMO,此错误消息是有争议的,因为它说,有错我没”吨作出,因为正如我所用的错误消息从第4行看到,堆栈跟踪指向方法声明体,这一个:

'tasks.remove' (taskId) { 
     check(taskId, String); 

     const task = Tasks.findOne(taskId); 
     if (task.owner !== Meteor.userId()) { // <- ERROR MESSAGE POINTS TO THIS LINE 
      // If the task is private, make sure only the owner can delete it 
      throw new Meteor.Error('not-authorized'); 
     } 

     Tasks.remove(taskId); 
    }, 

有教程℃之间1个差Ode和我的一个:我从我的if声明中删除了条件!todo.private,因此在原始教程中它们如下所示: if (!task.private && task.owner !== Meteor.userId()) {... IMO,此更改使测试达到表达失败的位置,因为测试通过了原始代码。

我还提到,将Meteor.userId()更改为this.userId可以使测试通过,并且该应用看起来也像以前一样工作。

所以,我的问题基本上是:为什么错误信息显示我有争议(IMO)的信息和在方法中使用this.userIdMeteor.userId()有什么区别? https://github.com/kemsbe/simple-todo

回答

1

基本上this.userId使用功能和Meteor.userId()使用当前光纤以获取用户标识的this方面:

我全“的Todo教程”项目代码可以在这里找到。

如果你想让你的代码与Meteor.userId()一起工作,你需要在光纤中运行你的函数。你可以做的另一件事是存根meteor.userId,就像在How to unit test a meteor method with practicalmeteor:mocha