gpt4 book ai didi

node.js - 使用 chai 检查 typescript/nodejs 中的异常不起作用

转载 作者:行者123 更新时间:2023-12-02 16:46:31 26 4
gpt4 key购买 nike

我在 typescript 代码中使用 chai 断言测试我的简单函数时遇到问题

我有:

    public async test1(){
throw (new Error(COUCH_CONNECTION_ERROR.message));
}

其中沙发连接错误是这样定义的:

export const COUCH_CONNECTION_ERROR: IErrorModel = {
code: "couch_connection_error",
message: "Unable to connect to Couchdb.",
};

现在我这样写了一个测试:

    it("test", ()=>{

console.log(obj.test1());
expect(obj.test1()).to.throw(Error, COUCH_CONNECTION_ERROR.message)
console.log(`ccccccccccccccccc`);
})

所以当我运行测试时,我得到了

AssertionError: expected {} to be a function

任何人都可以帮助理解我的测试有什么问题吗?

最佳答案

使用 mocha 和 chai async/await 风格:

import {expect} from "chai";

const test1 = async () => {
throw new Error("I AM THE ERROR");
};

describe("My test case", async () => {
it("should assert", async () => {

try {
await test1();
expect(true, "promise should fail").eq(false)
} catch (e) {
expect(e.message).to.eq("I AM THE EXPECTED ERROR");
}
});
});

使用 chai-as-promised :

import * as chai from "chai";
import * as chaiAsPromised from "chai-as-promised";

chai.use(chaiAsPromised);
const {expect} = chai;

const test1 = async () => {
throw new Error("I AM THE ERROR");
};

describe("My test case", async () => {
it("should assert", async () => {
await expect(test1()).to.eventually.be.rejectedWith("I AM THE EXPECTED ERROR");
});
});

使用 chai-as-promised,您还可以返回期望的 promise :

it("should assert", async () => {
return expect(test1()).to.eventually.be.rejectedWith("I AM THE EXPECTED ERROR");
});

在每种情况下,您都应该得到一个测试错误说明:

  1) My test case
should assert:

AssertionError: expected promise to be rejected with an error including 'I AM THE EXPECTED ERROR' but got 'I AM THE ERROR'
actual expected

I AM THE EXPECTED ERROR

关于node.js - 使用 chai 检查 typescript/nodejs 中的异常不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60342462/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com