2017-06-13 98 views
3

有一個簡單的方法,它拋出一個錯誤:摩卡/柴:測試精確投擲錯誤結果

methods.js

insertItem = new ValidatedMethod({ 
    name : 'article.insert.item', 
    validate: new SimpleSchema({ 
     parent: { type: SimpleSchema.RegEx.Id } 
     value : { type: String } 
    }).validator(), 

    run({ parent, value}) { 
     var isDisabled = true 
     if (isDisabled) 
      throw new Meteor.Error('example-error', 'There is no reason for this error :-)') 
    } 
}) 

現在我想做一個摩卡測試對於這個錯誤。所以,我想出了這個,這是工作:

server.test.js

it('should not add item, if element is disabled', (done) => { 
    const value = 'just a string' 

    function expectedError() { 
     insertItem.call(
      { 
       parent: '12345', 
       value 
      } 
     ) 
    } 

    expect(expectedError).to.throw 
    done() 
}) 

直到此時一切正常。

問題

但我想測試確切的錯誤信息。

我已經嘗試過

expect(expectedError).to.throw(new Meteor.Error('example-error', 'There is no reason for this error :-)')) 

但它給了我一個失敗的測試:

Error: expected [Function: expectedError] to throw 'Error: There is no reason for this error :-) [example-error]' 

回答

0

我認爲文檔是有點誤導/在這混亂 - 只是從你的expect刪除new操作它將匹配拋出的錯誤:

expect(expectedError).to.throw(Meteor.Error('example-error', 'There is no reason for this error :-)'))

+0

另外,你已經'var disabled = true'但是'if(isDisabled)'在下一行 - 但我假設這只是示例代碼沒有從你的函數複製 – rubie

+0

有了這個測試仍然失敗:''錯誤:期望[函數:expectedError]拋出一個錯誤' – user3142695

+0

@ user3142695我已經使用示例代碼測試了上述幾次,並引發了正確的錯誤。你是否刪除了'new'並且改變了'var disabled' /'if(isDisabled)'部分? – rubie

相關問題