我有一个字符串数组 names
,它会动态填充数据集中的名称。即使数据集发生变化,此数组中的三个名称始终相同。因此,在我的规范中,我想检查名称数组是否包含这三个特定名称。但是匹配器并没有在 Jasmine 中帮助我。
例子:
names = ["a", "b", "c", "d", "e", "f", "g"];
expect(names).toContain("b","d","c"); // this should return true as b, d, and c are in the names array
上面的 expect 语句不起作用。有没有办法使用 toMatch
并使用 regex
来解决这个问题?
谁能帮我解决这个问题。
谢谢。
最佳答案
除了使用 toContain()
,您还可以简单地实现以下函数并期望结果为 true 或 false。
function arrayContains(superset, subset) {
if (subset.length === 0) return false;
return subset.every(function (value) {
return (superset.indexOf(value) >= 0);
});
}
现在,您可以在 expect
语句中调用此函数,如下所示:
expect(arrayContains(names,["b", "d", "c"])).toBe(true);
正如您所提到的,这三个名称始终是预期的,您可以将其分配给一个变量,然后将其传递到上面的函数中。
希望对您有所帮助。如有必要,您甚至可以实现 customMatcher
。
关于javascript - 使用 Jasmine toContains 或 toMatch 进行字符串数组比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47316869/