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

How to spy an async function and assert that it throws an error by sinon?

我正在尝试使用 Mocha 和 ts-node 为我的项目在 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();
    });
});

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

您的函数是一个 async 函数。

async 函数的 docs 声明它们将 return:

A Promise which will be resolved with the value returned by the async function, or rejected with an uncaught exception thrown from within the async function.


换句话说,您的函数不会抛出错误,它return是一个 Promise 将拒绝并返回错误


由于您使用的是 Mocha,因此您可以使用 chai-as-promised 中的 .rejected 之类的东西来测试 Promise return 由您的 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
});