Chai 希望使用 Typescript 抛出不匹配相同异常的异常

Chai expect to throw Exception not matching same exception using Typescript

大家好,所以我一直在尝试编写一个单元测试来预期某种类型的异常。我有一个抛出该异常的函数,但我的测试仍然失败。为了排除故障,我已经尝试抛出相同的异常但仍然失败。我可以通过比较消息让它通过,但这似乎是一个糟糕的主意。

我应该如何处理匹配的自定义异常的测试?

Class代码

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);
}

赢了,谢谢!

您正在将错误 [​​=20=]实例 传递给 .throw(...) 方法。您需要传递一个 constructor 来代替。你传递给 expect 的必须是 expect 将调用的函数。您注释掉的行应编辑为:

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

您可以将一个实例传递给该方法,但当且仅当被测试函数引发的实例和您传递给 .throw(...) 的实例满足与 [=15= 的比较时,断言才会通过].也就是说,这两个值必须是完全相同的 JS 对象。在测试真实代码(而不是琐碎的示例)时,几乎不可能在引发错误之前获得错误实例,因此通常无法传递实例。