Based on the presence of a Jest d.ts
in the image, it can be inferred that this code snippet is related to Jest testing.
The .contain
method performs a strict comparison using ===
, which means it does not work for checking partial strings.
An alternative approach would be to search for the item in the array and verify its existence:
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();
});
The Array.find method returns the first element that matches the callback condition, or undefined if nothing is found.
If this verification needs to be done frequently, a custom matcher can be created in Jest as shown below:
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');
});
An example without a test assertion is provided below:
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)));