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
.
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"
})
])
);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With