9

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.

Federico Grandi
  • 6,785
  • 5
  • 30
  • 50
I'll-Be-Back
  • 10,530
  • 37
  • 110
  • 213

2 Answers2

23

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"
      })
    ])
  );
});
Federico Grandi
  • 6,785
  • 5
  • 30
  • 50
Win
  • 5,498
  • 2
  • 15
  • 20
1

Not a fan of that long answer, what will happen if you make one .some of the array and assert it returns false.

const hasItem = arr.some((item)=>item.UserId === 123);
expect(hasItem).toBe(true);

If you have some operation that is supposed to remove that item, I would do two expect statements, before the operation and after, so you validate it did exist before that.

vvn050
  • 194
  • 2
  • 4
  • Personal preference but I would avoid using Array.prototype.some in a test and rely on what the expect api was designed for. – Win Jan 11 '23 at 17:55