gpt4 book ai didi

javascript - 如何断言数组包含 JavaScript/脚本中的子字符串

转载 作者:行者123 更新时间:2023-12-03 16:47:12 32 4
gpt4 key购买 nike

我正在尝试检查数组中是否存在 SubString。在测试中我断言使用:

expect(classList).toContain('Rail__focused')
我收到以下错误:
Error: expect(received).toContain(expected // indexOf
Expected value: "Rail__focused"
Received array: ["Rail__item__3NvGX", "Rail__focused__3bGTR", "Tile__tile__3jJYQ", "Tile__wide__1GuVb", "Tile__animated__3H87p", "Tile__active__1mtVd"]
这就是我想要实现的,并希望它通过

var arr = ["Rail__item__3NvGX", "Rail__focused__3bGTR", "Tile__tile__3jJYQ", "Tile__wide__1GuVb", "Tile__animated__3H87p", "Tile__active__1mtVd"];

var str = 'Rail__focused';
for (var i = 0, len = arr.length; i < len; ++i) {
if (str.indexOf(arr[i]) != -1) {
console.log("This is a pass")
} else {
console.log("This is a fail")
}
}

enter image description here

最佳答案

所以因为有一个笑话d.ts在屏幕截图中 - 我只是假设这是开玩笑 :).contain does a strict ===检查 - 所以这不适用于部分字符串。
例如,您可以在数组中搜索项目并断言它存在:

test('contain', () => {
const classList = [
'Rail__item__3NvGX',
'Rail__focused__3bGTR',
'Tile__tile__3jJYQ',
'Tile__wide__1GuVb',
'Tile__animated__3H87p',
'Tile__active__1mtVd',
];
expect(classList.find((el) => el.includes('Rail__focused'))).toBeDefined();
});
Array.find将返回满足回调结果的第一个元素。它将返回 undefined - 如果没有找到。
如果这是一个重复的任务 - 你可以写一个 custom matcher in Jest :
expect.extend({
toPartiallyContain(received, needle) {
const pass = received.find((el) => el.includes(needle));
if (pass) {
return {
message: () =>
`expected ${received} not to partially contain ${needle}`,
pass: true,
};
} else {
return {
message: () => `expected ${received} to partially contain ${needle}`,
pass: false,
};
}
},
});

test('contain with custom matcher', () => {
const classList = [
'Rail__item__3NvGX',
'Rail__focused__3bGTR',
'Tile__tile__3jJYQ',
'Tile__wide__1GuVb',
'Tile__animated__3H87p',
'Tile__active__1mtVd',
];
expect(classList).toPartiallyContain('Rail__focused');
expect(classList).not.toPartiallyContain('Hello');
});
您的示例没有测试断言:

var arr = ["Rail__item__3NvGX", "Rail__focused__3bGTR", "Tile__tile__3jJYQ", "Tile__wide__1GuVb", "Tile__animated__3H87p", "Tile__active__1mtVd"];

var str = 'Rail__focused';

console.log(arr.find((el) => el.includes(str)));

关于javascript - 如何断言数组包含 JavaScript/脚本中的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65380534/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com