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

时间:2017-09-02 21:30:27

标签: typescript exception tdd mocha chai

Ello all,所以我一直在尝试编写一个期望某种类型的异常的单元测试。我有一个抛出异常的函数但是,我仍然有一个失败的测试。为了排除故障,我只是试图抛出相同的异常并仍然失败。我可以通过比较消息来通过,但这似乎是一个可怕的想法。

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

班级代码

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 个答案:

答案 0 :(得分:1)

您正在将错误实例传递给.throw(...)方法。您需要传递构造函数。您传递给expect的内容必须是expect将调用的函数。您的注释掉的行应编辑为:

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

您可以将实例传递给方法,但是当且仅当被测试函数引发的实例和传递给.throw(...)的实例满足与===的比较时,断言才会传递。换句话说,这两个值必须是完全相同的JS对象。在测试真实代码(而不是简单的例子)时,几乎不会出现错误提升之前可以获取错误实例的情况,因此传递实例是您通常无法做到的事情。