Lea*_*ner 2 unit-testing node.js chai typescript
我在打字稿代码中使用 chai 断言测试我的简单函数时遇到问题
我有:
public async test1(){
throw (new Error(COUCH_CONNECTION_ERROR.message));
}
Run Code Online (Sandbox Code Playgroud)
其中沙发连接错误是这样定义的:
export const COUCH_CONNECTION_ERROR: IErrorModel = {
code: "couch_connection_error",
message: "Unable to connect to Couchdb.",
};
Run Code Online (Sandbox Code Playgroud)
现在我这样写了一个测试:
it("test", ()=>{
console.log(obj.test1());
expect(obj.test1()).to.throw(Error, COUCH_CONNECTION_ERROR.message)
console.log(`ccccccccccccccccc`);
})
Run Code Online (Sandbox Code Playgroud)
所以当我运行测试时我得到
AssertionError: expected {} to be a function
Run Code Online (Sandbox Code Playgroud)
谁能帮助理解我的测试出了什么问题?
使用 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");
}
});
});
Run Code Online (Sandbox Code Playgroud)
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");
});
});
Run Code Online (Sandbox Code Playgroud)
使用chai-as-promised,您还可以返回期望承诺:
it("should assert", async () => {
return expect(test1()).to.eventually.be.rejectedWith("I AM THE EXPECTED ERROR");
});
Run Code Online (Sandbox Code Playgroud)
在每种情况下,您都应该收到一个测试错误,指出:
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
Run Code Online (Sandbox Code Playgroud)