首页 > 解决方案 > 在 Jest 中使用 toMatchObject 和 stringMatching(regexp)

问题描述

我正在使用 JEST 匹配器toMatchObject来确保对象包含多个属性并且一些值是静态的,而其他一些值应该与特定的正则表达式匹配

问题是:当静态值不匹配时,输出也会显示正则表达式值不匹配,尽管它们很好

代码:

test("asdf", async () => {
  const actual = {
    a: "a_value",
    b: "b_value", 
    c: "c_value"
  }
  expect(actual).toMatchObject({
    a: expect.stringMatching("[a-z]_value"), 
    b: "b_value", 
  })

  expect(actual).toMatchObject({
    a: expect.stringMatching("[a-z]_value"), 
    b: "B_VALUE", 
  })
})

输出:

Expected value to match object:
  {"a": StringMatching /[a-z]_value/, "b": "B_VALUE"}
Received:
  {"a": "a_value", "b": "b_value", "c": "c_value"}
Difference:
- Expected
+ Received

  Object {
-   "a": StringMatching /[a-z]_value/,
-   "b": "B_VALUE",
+   "a": "a_value",
+   "b": "b_value",
  }

我想在这里的输出中看到不匹配的值,因为正则表达式很好:

   Object {
    -   "b": "B_VALUE",
    +   "b": "b_value",

例子

标签: typescriptjestjs

解决方案


这似乎是开玩笑的错误, https://github.com/facebook/jest/issues/6928


推荐阅读