2017-09-02 67 views
0

Ello all,所以我一直在試圖編寫一個單元測試,預計某種類型的異常。我有一個拋出該異常的函數,但是我仍然遇到了一個失敗的測試。爲了排除故障,我儘可能拋出相同的異常並仍然失敗。我可以通過比較消息來通過,但這似乎是一個可怕的想法。柴期望拋出異常不匹配使用Typescript相同的異常

我該如何處理匹配自定義異常的測試?

類代碼

export class EventEntity { 

    comments : Array<string> = new Array<string>(); 

    constructor() {} 

    public addComment(comment : string) { 
     this.comments.push(comment); 
    } 

    public getCommentCount() : number { 
     return this.comments.length; 
    } 

    public getCommentByOrder(commentNumber : number) : string { 
     console.log(`getCommentByOrder with arg:${commentNumber}`);    

     let offset = 1; 
     try { 
      let result = this.comments[commentNumber - offset]; 
      return result; 
     } catch (err){ 
       console.log(`getCommentByOrder:Error: ${err.toString()}`); 
      console.log(`err: with arg:${commentNumber}`); 
      if(err instanceof RangeError){ 
       throw new CommentNotFoundException(); 
      } 
      throw err; 
     } 
    } 
} 

MyException
export class CommentNotFoundException extends Error { 
    constructor(m?:string) 
    { 
     let message : string = m?m:"Comment number not found in event's comments.";   
     super(message); 
     Object.setPrototypeOf(this, CommentNotFoundException.prototype); 
    } 
} 

失敗測試

@test shouldThrowIfCommentNumberIsGreaterThanTotalNumberOfComments() { 
    let testEvent = new EventEntity(); 
    let expectedException = new CommentNotFoundException(); 
    //expect(testEvent.getCommentByOrder(5)).to.throw(expectedException); 
    expect(()=> { 
     throw new CommentNotFoundException(); 
    }).to.throw(new CommentNotFoundException()); 
} 

更新

好,我修改了。這按預期工作。唯一的例外是沒有被拾起形式:

expect(testEvent.getCommentByOrder(5)).to.throw(CommentNotFoundException); 

但確實:

expect(()=>{ 
     testEvent.getCommentByOrder(5); 
}).to.throw(CommentNotFoundException); 

這裏是更新的代碼上市交易:

方法

public getCommentByOrder(commentNumber : number) : string { 
    let offset = 1; 
    let result = this.comments[commentNumber - offset]; 
    if (!result) { 
     throw new CommentNotFoundException(); 
    } else { 
     return result; 
    } 
} 

測試

@test shouldThrowIfCommentNumberIsGreaterThanTotalNumberOfComments() { 
    let testEvent = new EventEntity(); 
    expect(()=>{ 
      testEvent.getCommentByOrder(5); 
    }).to.throw(CommentNotFoundException); 
} 

這是一個勝利,謝謝!

回答

1

您正在向.throw(...)方法傳遞錯誤實例。您需要改爲通過構造函數。而你傳遞給expect的函數必須是expect將要調用的函數。您註釋掉線應編輯:

expect(() => testEvent.getCommentByOrder(5)).to.throw(CommentNotFoundException); 

你可以傳遞一個實例的方法,但隨後的斷言將通過當且僅當被測試的功能提出的實例,並傳遞給.throw(...)實例滿足與===比較。換句話說,這兩個值必須是完全相同的JS對象。在測試真實代碼(而不是簡單的例子)時,幾乎不會出現在錯誤發生之前獲取錯誤實例,因此傳遞實例通常無法實現的情況。

+0

這不是確切的解決方案,但完全讓我走上了正確的道路。謝謝!!! – Terrance

+0

您可能在[上次編輯](https://stackoverflow.com/revisions/46018605/2)之前閱讀我的答案。不幸的是,SO崩潰了編輯接連完成,但我最後的編輯是改變傳遞給'expect'的參數,使其成爲一個函數。我最初鎖定在構造函數和實例問題上,錯過了。 – Louis