Explore detailed aspects of Jest matchers with this quiz, focusing on deep equality, truthiness checks, and advanced assertion scenarios. Sharpen your skills in the tools ecosystem by identifying the right matcher for common testing challenges.
When validating if two JavaScript objects have identical nested properties and values, which Jest matcher should you use to check deep equality?
Explanation: The correct choice is toEqual because it performs a deep equality check on objects and arrays, comparing their nested properties. toBe checks for strict reference equality, so it would fail for different but identical objects. toMatch is typically used for string or regular expression comparisons, not for objects. toDeepEqual may sound correct, but it is not an actual matcher in Jest; instead, use toEqual.
Which Jest matcher would you use to test if an object, such as {status: 'active', id: 3}, contains a specific property without checking the property's value?
Explanation: toHaveProperty is specifically designed to assert the presence of a property on an object, regardless of its value. toBeDefined only checks if a variable is not undefined, not properties within objects. toMatchObject can compare properties and values, but does not only check for presence. toOwnProperty is not a matcher in Jest, making it invalid here.
If you want to check that an array contains all expected elements, like [1, 2, 3], but the order does not matter, which matcher should you choose?
Explanation: toContainEqual is correct because it checks if the array contains an element with the expected value, using deep equality, regardless of order. toContain only checks for a specific primitive or reference, not objects or deep equality. toHaveLength asserts the array's size but not its contents. toEqual would require an exact match, including order and all values.
Given a value set to null, which Jest matcher is most appropriate to confirm its nullness in a test?
Explanation: toBeNull is the explicit matcher for asserting that a value is exactly null and nothing else. toBeFalsy would also pass for other falsy values like 0 or undefined, not just null. toBeUndefined is for checking if a value is strictly undefined. toBeNaN checks for Not-a-Number, which is unrelated to null values.
Which matcher is most appropriate for checking if two floating point numbers, like 0.2 + 0.1 and 0.3, are approximately equal in Jest?
Explanation: toBeCloseTo is designed for comparing floating point numbers with a specified precision, handling minor rounding errors. toBe requires strict equality, which often fails with floating point math. toEqual is also strict and may produce unexpected failures with floating point decimals. toMatchFloat is not a valid Jest matcher and would cause errors.