Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check that a string contains one of the substring from an array with Jest

expectedStrings = [
'abc',
'def',
'ghi'
]
stringToCheck = 'zyxabc'

I want to check if stringToCheck contains one of the strings of expectedStrings with Jest. I have seen stringContaining and arrayContaining methods but I'm not sure how should I compose to make the test work.

I would like to use something close to this example :

describe('stringMatching in arrayContaining', () => {
  const expected = [
    expect.stringMatching(/^Alic/),
    expect.stringMatching(/^[BR]ob/),
  ];
  it('matches even if received contains additional elements', () => {
    expect(['Alicia', 'Roberto', 'Evelina']).toEqual(
      expect.arrayContaining(expected),
    );
  });
  it('does not match if received does not contain expected elements', () => {
    expect(['Roberto', 'Evelina']).not.toEqual(
      expect.arrayContaining(expected),
    );
  });
});
like image 535
Quentin Del Avatar asked Sep 02 '25 05:09

Quentin Del


1 Answers

I don't think combining arrayContaining and stringContaining is the best and most readable approach here (If even possible at all).

Instead simply try this method:

    const numberOfMatches = expectedStrings.filter(x => stringToCheck.indexOf(x) > -1).length;
    expect(numberOfMatches).toBeGreaterThan(0);
like image 124
yadejo Avatar answered Sep 04 '25 17:09

yadejo