如何监视异步函数并断言它会抛出sinon的错误?

问题描述 投票:1回答:1

我正在尝试使用带有ts节点的Mocha为我的项目在TypeScript中编写单元测试。当我使用sinon来制造异步函数的间谍时,我无法获得测试通过。以下是我的代码

class MyClass {
    async businessFunction(param): Promise<void> {
        if (!param)  //Validate the input
          throw new Error("input must be valid");

        // Then do my business
    }
}

和单元测试

describe("The feature name", () => {
    it("The case of invalid", async () => {
        const theObject = new MyClass();
        const theSpider = sinon.spy(theObject, "businessFunction");
        try {
            await theObject.businessFunction(undefined);
        } catch (error) {/* Expected error */}
        try {
            await theObject.businessFunction(null);
        } catch (error) {/* Expected error */}

        sinon.assert.calledTwice(theSpider); // => Passed
        sinon.assert.alwaysThrew(theSpider); // => Failed, why?

        theSpider.restore();
    });
});

有没有人有经验来处理这个问题?我被建议用捕获的错误进行检查,但它似乎很复杂,并且使得检查代码不必要地重复。

javascript typescript async-await mocha sinon
1个回答
2
投票

你的功能是async功能。

docs函数的async声明它们将返回:

Promise将使用async函数返回的值进行解析,或者在异步函数中抛出未捕获的异常而被拒绝。


换句话说,你的函数不会抛出错误,它会返回一个Promise,它将拒绝错误。


既然你正在使用Mocha,你可以使用.rejectedchai-as-promised来测试你的Promise函数返回的async拒绝:

it("The case of invalid", async () => {
  const theObject = new MyClass();

  await theObject.businessFunction(undefined).should.be.rejected;  // SUCCESS
  await theObject.businessFunction(null).should.be.rejected;  // SUCCESS
});
© www.soinside.com 2019 - 2024. All rights reserved.