无法测试预期抛出的异步方法

时间:2018-05-21 00:59:39

标签: node.js typescript asynchronous async-await mocha

我有一个看起来像这样的测试用例:

it("should throw when the template file does not exist", async (): Promise<void> => {
    await expect(new UpdateReadmeCommandlet().invoke()).to.be.rejectedWith(Error);
});

相应的invoke方法如下:

public async invoke(): Promise<void> {
    fs.readFile(this.templatePath, (outerError: NodeJS.ErrnoException, data: Buffer): void => {
        if (outerError !== null) {
            throw new Error(`FileNotFoundException: Cannot find file \`${this.templatePath}'.`);
        }
    });
}

设置此测试以便抛出此错误。在运行mocha时,我收到一些非常笨拙的错误消息,一切都到处都是,这很可能是由于异步调用。我得到的错误消息是AssertionError: expected promise to be rejected with 'Error' but it was fulfilled with undefined

我的测试是基于this answer编写的。令人惊讶的是,当我复制fails方法时,它按照帖子中的描述工作。通过调用throw来交换invoke指令会导致问题。所以我假设我的invoke方法必须以不同的方式工作。

我仍然无法弄清楚实际上是什么错误以及如何重写我的测试s.t.不会干扰其他测试并正确检查我的断言。

1 个答案:

答案 0 :(得分:1)

传递给fs.readFile 的回调不会拒绝public async invoke(): Promise<void> {

返回的承诺

修复

fs.readFile包裹为异步识别并使用级联承诺拒绝。

public async invoke(): Promise<void> {
    return new Promise<void>((res, rej) => {
    fs.readFile(this.templatePath, (outerError: NodeJS.ErrnoException, data: Buffer): void => {
        if (outerError !== null) {
            rej(new Error(`FileNotFoundException: Cannot find file \`${this.templatePath}'.`));
        }
    });

    })
}
相关问题