我在打字稿代码中使用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
任何人都可以帮助您了解我的考试有什么问题吗?
使用摩卡和chai异步/等待样式:
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");
}
});
});
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
,您还可以返回期望的承诺:
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