无法测试预期会抛出的异步方法
Cannot test an async method that is expected to throw
我有一个如下所示的测试用例:
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
方法时,它按照 post 中的描述工作。将 throw
指令与我对 invoke
的调用交换会导致问题。所以我假设我的 invoke
方法必须以不同的方式工作。
我仍然无法弄清楚到底哪里出了问题以及如何重写我的测试 s.t。不会干扰其他测试并正确检查我的断言。
传递给 fs.readFile
的回调中的 throw 不会 拒绝 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}'.`));
}
});
})
}
我有一个如下所示的测试用例:
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
方法时,它按照 post 中的描述工作。将 throw
指令与我对 invoke
的调用交换会导致问题。所以我假设我的 invoke
方法必须以不同的方式工作。
我仍然无法弄清楚到底哪里出了问题以及如何重写我的测试 s.t。不会干扰其他测试并正确检查我的断言。
传递给 fs.readFile
的回调中的 throw 不会 拒绝 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}'.`));
}
});
})
}