【问题标题】:When to use expect.stringContaining instead of toContain for substring matching in Jest何时在 Jest 中使用 expect.stringContaining 而不是 toContain 进行子字符串匹配
【发布时间】:2021-01-17 10:52:26
【问题描述】:

使用stringContaining 而不是仅使用toContain 与Jest 进行子字符串匹配的用例是什么?

it("tests with stringContaining", () => {
  expect("testerama").toEqual(expect.stringContaining("test"))
})
it("tests with toContain", () => {
  expect("testerama").toContain("test")
})

据我所知,除了字符串是nullundefined 之外,行为是相似的,stringContaining 错误消息更清晰一些。

Expected: StringContaining "test"
Received: null

相对

Matcher error: received value must not be null nor undefined
Received has value: null

对于不那么简洁的代码似乎不值得。我错过了什么吗?

【问题讨论】:

  • 我猜stringContaining 的一个优点是它会在 array 上失败,所以如果你期望的实际上是一个子字符串,它会更具体一些,因此更安全,而toContain 有双重职责。不过,IMO 的可读性较差。
  • 是的,我完全同意,谢谢????

标签: jestjs


【解决方案1】:

唯一真正的区别是expect.stringContaining 方法由社区维护,而expect.toContain 是官方 Jest API 的一部分。

【讨论】:

    猜你喜欢
    • 2021-08-13
    • 2017-06-14
    • 1970-01-01
    • 2015-08-17
    • 1970-01-01
    • 1970-01-01
    • 2021-07-22
    • 1970-01-01
    • 2011-08-30
    相关资源
    最近更新 更多