我正在尝试使用带有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();
});
});
有没有人有经验来处理这个问题?我被建议用捕获的错误进行检查,但它似乎很复杂,并且使得检查代码不必要地重复。
你的功能是async
功能。
docs函数的async
声明它们将返回:
Promise
将使用async函数返回的值进行解析,或者在异步函数中抛出未捕获的异常而被拒绝。
换句话说,你的函数不会抛出错误,它会返回一个Promise
,它将拒绝错误。
既然你正在使用Mocha
,你可以使用.rejected
的chai-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
});