JEST Asymmetric Matchers
Introduction
Asymmetric matchers in Jest are matchers that do not require an exact equality between the actual value and the expected value. Instead, they allow for more flexible matching conditions. This is useful when you want to assert that an object or value meets certain criteria but don't need it to be an exact match.
Jest provides a few built-in asymmetric matchers, such asexpect.anything(),expect.any(),expect.arrayContaining(),expect.objectContaining(),expect.stringContaining(), andexpect.stringMatching().
Asymmetric matchers can be particularly useful when working with complex data structures or when the exact value isn't as important as the presence of certain elements or properties. They provide a powerful way to write more flexible and maintainable tests.expect.anything()
Matches anything except
nullorundefined.test('matches anything except null or undefined', () => { expect(42).toEqual(expect.anything()); expect('string').toEqual(expect.anything()); expect(null).not.toEqual(expect.anything()); expect(undefined).not.toEqual(expect.anything()); });expect.any(constructor)
Matches anything that is of the type provided.
test('matches any number', () => { expect(42).toEqual(expect.any(Number)); expect('string').not.toEqual(expect.any(Number)); });expect.arrayContaining(array)
Matches if the received array contains all of the elements in the expected array.
test('matches arrays that contain the expected elements', () => { expect([1, 2, 3]).toEqual(expect.arrayContaining([2, 3])); expect([1, 2, 3]).not.toEqual(expect.arrayContaining([4])); });expect.objectContaining(object)
Matches if the received object contains all of the key/value pairs in the expected object.
test('matches objects that contain the expected key/value pairs', () => { expect({a: 1, b: 2, c: 3}).toEqual(expect.objectContaining({a: 1, c: 3})); expect({a: 1, b: 2, c: 3}).not.toEqual(expect.objectContaining({d: 4})); });expect.stringContaining(string)
Matches if the received string contains the expected substring.
test('matches strings that contain the expected substring', () => { expect('hello world').toEqual(expect.stringContaining('hello')); expect('hello world').not.toEqual(expect.stringContaining('goodbye')); });expect.stringMatching(regex)
Matches if the received string matches the expected regular expression.
test('matches strings that match the expected regex', () => { expect('hello world').toEqual(expect.stringMatching(/hello/)); expect('hello world').not.toEqual(expect.stringMatching(/goodbye/)); });