使用Jest检查字符串是否包含数组中的子字符串之一

时间:2019-03-11 16:31:16

标签: javascript jestjs

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),
    );
  });
});

1 个答案:

答案 0 :(得分:1)

我不认为将arrayContaining和stringContaining结合起来是最好和最易读的方法(即使可能的话)。

相反,只需尝试以下方法:

    const numberOfMatches = expectedStrings.filter(x => stringToCheck.indexOf(x) > -1).length;
    expect(numberOfMatches).toBeGreaterThan(0);