expect.stringMatching(string | regexp)

expect.stringMatching(string | regexp) matches the received value if it is a string that matches the expected string or regular expression.

You can use it instead of a literal value:

  • in toEqual or toBeCalledWith
  • to match an element in arrayContaining
  • to match a property in objectContaining or toMatchObject
    This example also shows how you can nest multiple asymmetric matchers, with expect.stringMatching inside the expect.arrayContaining.
  1. describe('stringMatching in arrayContaining', () => {
  2. const expected = [
  3. expect.stringMatching(/^Alic/),
  4. expect.stringMatching(/^[BR]ob/),
  5. ];
  6. it('matches even if received contains additional elements', () => {
  7. expect(['Alicia', 'Roberto', 'Evelina']).toEqual(
  8. expect.arrayContaining(expected),
  9. );
  10. });
  11. it('does not match if received does not contain expected elements', () => {
  12. expect(['Roberto', 'Evelina']).not.toEqual(
  13. expect.arrayContaining(expected),
  14. );
  15. });
  16. });