测试数组是否不包含值

时间:2019-01-26 17:12:59

标签: javascript node.js jestjs

是否可以使用Jest验证userId: 123不存在。
例如:

[
  { UserId: 112, Name: "Tom" },
  { UserId: 314, Name: "Paul" },
  { UserId: 515, Name: "Bill" }
]

如果没有UserId: 123的对象,则测试应通过。

2 个答案:

答案 0 :(得分:1)

执行此操作的正确方法是检查数组是否不等于将包含要验证的对象的数组。下面提供的示例向您展示如何通过将arrayContainingobjectContaining分层来实现此目的。

it("[PASS] - Check to see if the array does not contain John Smith", () => {
  expect([
    {
      user: 123,
      name: "Amelia Dawn"
    }
  ]).not.toEqual(
    expect.arrayContaining([
      expect.objectContaining({
        user: 5,
        name: "John Smith"
      })
    ])
  );
});

it("[FAILS] - Check to see if the array does not contain John Smith", () => {
  expect([
    {
      user: 5,
      name: "John Smith"
    },
    {
      user: 123,
      name: "Amelia Dawn"
    }
  ]).not.toEqual(
    expect.arrayContaining([
      expect.objectContaining({
        user: 5,
        name: "John Smith"
      })
    ])
  );
});

答案 1 :(得分:0)

一个简单的forEach循环就可以解决问题。

users = [
{ UserId: 112, Name: "Tom" },
{ UserId: 314, Name: "Paul" },
{ UserId: 515, Name: "Bill" }
]

function checkUserId(id) {
users.forEach(function(user) {
    if user.UserId === id {
    return False
    }
});
return True

}

checkUserId(123) //returns True
checkUserId(112) //returns False

编辑

很抱歉,如果这样做没有帮助。在发布此问题后,我才注意到您问题的笑话。

相关问题