Fri Jan 20 2023
Partial matching objects, nested objects, arrays and nested objects in arrays using Jest
A guide into how to use jest matchers to do partial matching for data inside objects and arrays (even when nested)
I was recently rewriting some legacy tests to use Jest and noticed that some tests were unusually long as the assertions contained data that weren't even relevant to the test. We don't need to assert a whole big object or array since jest allows us to test our assertions with partial matching. Here are a few examples
The most straight forward isEqual
1it("testing identical objects with toEqual", () => {2 const object = {3 name: "James",4 age: 28,5 };6 expect(object).toEqual({ name: "James", age: 28 });7});
Partial matching with an object
1it("partial matching with an object", () => {2 const object = {3 name: "James",4 age: 28,5 };6 expect(object).toEqual(7 expect.objectContaining({8 name: "James",9 })10 );11});12
Partial matching to a nested object
1it("partial matching to a nested object", () => {2 const object = {3 name: "James",4 age: 28,5 locationData: {6 country: "Poland",7 },8 };9 expect(object).toEqual(10 expect.objectContaining({11 locationData: expect.objectContaining({12 country: "Poland",13 }),14 })15 );16});17
Testing identical arrays with toEqual
1it("testing identical arrays with toEqual", () => {2 const array = ["Sam"];3 expect(array).toEqual(["Sam"]);4});
Partial matching properties in an array
1it("partial matching properties in an array ", () => {2 const array = ["Sam", "James"];3 expect(array).toEqual(expect.arrayContaining(["James"]));4});
Partial matching properties of an object in an array
1it("partial matching properties of an object in an array ", () => {2 const array = ["Sam", "James", { name: "Misia" }];3 expect(array).toEqual(4 expect.arrayContaining([5 expect.objectContaining({6 name: "Misia",7 }),8 ])9 );10});11
If you want to play with the above, I have the code pushed to this repository for you to experiment with.
I hope the above helps you write cleaner and shorter tests! Until next time!