You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 23:54:01