Chai断言传入空字符串作为预期错误信息时测试仍通过是否正常?
这是Chai断言库的正常设计行为
- Chai的
.throw()断言传入字符串类型的预期错误信息参数时,默认执行子串包含匹配,而非严格的全量相等匹配:- 空字符串
""是所有字符串的默认子串,因此只要函数确实抛出了Error类型的错误,无论实际错误信息是什么,该断言都会判定通过。 - 你传入的单个空格
" "本身就存在于目标错误信息的多个位置,子串匹配判定命中,因此测试也会通过。
- 空字符串
严格匹配完整错误信息的写法
如果需要校验错误信息和预期完全一致,可以用以下两种写法:
写法1:传入全量匹配正则
it("should get no module, since no abc", () => { expect(ModuleProcess.filterTypeModules.bind(ModuleProcess, "abc", mockFilterTypeLists.fullType)) .to.throw(Error, /^No matched module found when filtered with Type abc, JSON is null\.$/) })
写法2:单独断言错误的message属性(可读性更高)
也可以直接用箭头函数包裹待测试代码替代bind写法,逻辑更直观:
it("should get no module, since no abc", () => { expect(() => ModuleProcess.filterTypeModules("abc", mockFilterTypeLists.fullType)) .to.throw(Error) .and.have.property("message", "No matched module found when filtered with Type abc, JSON is null.") })
内容的提问来源于stack exchange,提问作者Yanwt
相关产品推荐
相关产品推荐

