Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing if an array does not contain a value

Is it possible using Jest to validate that userId: 123 should not exist.
For example:

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

The test should pass if there's no object with UserId: 123.

like image 546
I'll-Be-Back Avatar asked Dec 17 '22 18:12

I'll-Be-Back


1 Answers

The correct way to do it is to check if the array does not equal the array that will contain the object that you're trying to validate against. The example provided below show's you how to achieve this by layering arrayContaining and objectContaining.

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"
      })
    ])
  );
});
like image 84
Win Avatar answered Jan 04 '23 04:01

Win