2017-05-09 30 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