我是使用mocha和chai在node.js中进行单元测试的新手。我陷入了控制自动返回而不执行的问题chai.expect(123(.to.be.a("字符串"(;
代码在这里
it.only("should fetch status",()=>{
return chai.request(server)
.get("/user/status")
.then((result)=>{
let data = result.body;
console.log("till here execute");
//this line is not executed and test case is passed even when the below line expect to fail the test
chai.expect(123).to.be.a("string");
})
.catch(err=>err);
});
控制台显示上面的测试用例通过了我不知道是如何以及为什么通过的
chai.expect(123).to.be.a("string");
不执行
这与您的catch
有关。
基本上,当你的chai.expect
失败时,它会抛出一个AssertionError
。
在给定的代码中,您返回捕获错误,而不是抛出错误。
根据chai.js官方文件,在https://www.chaijs.com/plugins/chai-http/,在处理promise时,必须在catch
中throw
捕获错误。
这样,改变:
.catch(err=>err);
至:
.catch(err => {throw err});