Ello all、私は特定のタイプの例外を期待する単体テストを書くことを試みてきました。私はその例外を投げた関数を持っていましたが、まだ失敗したテストがあります。トラブルシューティングのために、私は同じ例外をスローしようとしていて、まだ失敗に終わっています。私はメッセージを比較することで合格させることができますが、それはひどい考えのようです。Chaiは例外をスローすることを予期しています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);
}
これは勝利です、ありがとう!
これは正確な解決策ではありませんでしたが、まさに私を正しい道に導いてくれました。ありがとうございました!!! – Terrance
あなたはおそらく[最終編集](https://stackoverflow.com/revisions/46018605/2)の前に私の答えを読んでいます。残念ながら、SOは連続して行われる編集を崩壊させますが、最後の編集は 'expect'に渡された引数を変更して関数にすることでした。私は最初にコンストラクタとインスタンスの問題をラッチし、それを逃していた。 – Louis