chai 检查字符串数组中是否有一个带有子集字符串的字符串

问题描述 投票:0回答:3

我有一个字符串数组

['abc,'def','ghi','jkl']

我的字符串 B 等于

'j'

我想检查数组中是否有任何元素将字符串 B 作为子字符串

chai

这可能吗?我似乎不知道如何使用 chai 中的

.any
来测试数组中的每个元素是否匹配

我尝试了很多方法,包括但不限于:

expect(array).any.to.contain(string)
expect(array).any.to.have.string(string)
expect(array)to.have.any.string(string)

有没有一种优雅的方法来测试这个?

chai
3个回答
10
投票

有多种方法可以实现此目的,具体取决于您的搜索条件。

如果您正在查找单个字符(如示例所示),您可以连接数组字符串,然后检查包含该字符的结果字符串。如果您正在寻找多字符字符串,则此方法可能效果不佳,因为您可能会拾取一个条目的结尾并成为下一个条目的开头。如果您知道您的字符串永远不会包含给定字符,那么您可以引入分隔符。

expect(array.join()).to.include(single_character);
// or assuming your array will never include pipe (|)
expect(array.join('|').to.include(string);

或者,您可以使用 .some() 方法搜索数组并断言结果为 true。

expect(array.some(x => x.includes(string))).to.be.true;

0
投票

通过阅读之前的一些答案,想出了这个用于断言的辅助函数:

/**
 * Tests the schema errors and evaluates if a substring is contained within the errors.
 * @param validData - Data to be validated.
 * @param substring - Evaluated substring.
 * @param message - Mocha assertion message.
 * @returns {void}
 */
function expectSchemaErrorsToContain(validData: any, substrings: readonly string[], message?: string): void {
  const errors: string[] = getSchemaErrors(validData, dataSchema);
  const stringifiedErrors = JSON.stringify(errors, null, 0);
  for (const substring of substrings) {
    expect(stringifiedErrors, message).to.include(substring);
  }
  // Non-substring alternative:
  // expect(getSchemaErrors(validData, dataSchema)).to.include.members(substrings);
}

这是一个简单的例子:

_.set(validData, 'db', {});
expectSchemaErrorsToContain(validData, [
  '/db/connectionString is a required field',
  '/db/dbName is a required field',
]);

您可能希望使其适应您的代码。


-1
投票

您可能想使用

include
方法:

expect(array).to.include('string')
© www.soinside.com 2019 - 2024. All rights reserved.