大家好,所以我一直在尝试编写一个需要某种类型异常的单元测试。我有一个函数引发了该异常,但是我仍然得到了失败的测试。为了排除故障,我已经尝试抛出相同的异常,但仍然失败。我可以通过比较消息来让它通过,但这似乎是一个糟糕的主意。
我应该如何处理匹配的自定义异常的测试?
类代码
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;
}
}
}
我的异常
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);
}
这是一场胜利,谢谢!
最佳答案
您正在将错误实例传递给.throw(...)
方法。您需要传递一个构造函数。并且您传递给 expect
的必须是 expect
将调用的函数。您注释掉的行应编辑为:
expect(() => testEvent.getCommentByOrder(5)).to.throw(CommentNotFoundException);
您可以将实例传递给该方法,但当且仅当由正在测试的函数引发的实例和您传递给 .throw(...)
的实例满足时,断言才会通过与 ===
的比较。换句话说,这两个值必须是完全相同的 JS 对象。在测试真实代码(而不是简单的示例)时,几乎不可能在引发错误之前获取错误实例,因此通常无法传递实例。
关于typescript - Chai 期望使用 Typescript 抛出与相同异常不匹配的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46018381/