检查字符串是否包含具有Jest的数组中的一个子字符串

问题描述 投票:1回答:1
expectedStrings = [
'abc',
'def',
'ghi'
]
stringToCheck = 'zyxabc'

我想检查stringToCheck是否包含带有Jest的expectedStrings字符串之一。我见过stringContaining和arrayContaining方法,但我不知道应该如何构建才能使测试工作。

我想使用接近这个例子的东西:

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),
    );
  });
});
javascript jestjs
1个回答
2
投票

我不认为组合arrayContaining和stringContaining是最好的和最可读的方法(如果可能的话)。

而只是尝试这种方法:

    const numberOfMatches = expectedStrings.filter(x => stringToCheck.indexOf(x) > -1).length;
    expect(numberOfMatches).toBeGreaterThan(0);
© www.soinside.com 2019 - 2024. All rights reserved.