Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Assert a array contains a sub string in JavaScript/TScript

I am trying to check a SubString exists in an array. In the Test i am asserting using:

expect(classList).toContain('Rail__focused')

I am getting the following error:

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"]

This is what I wanted to achieve and wanted this to pass

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

like image 470
MNB Avatar asked Dec 20 '20 13:12

MNB


1 Answers

So because there is a Jest d.ts in the screenshot - I just assume that this is Jest :)

.contain does a strict === check - so this will not work with partial strings.

You could, for example, search for the item in the array and assert that it exists:

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 will return the first element that satisfies the callback result. It will return undefined - if nothing is found.

If this is a repeating task - you can write a 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');
});

Your example without a test assertion:

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)));
   
like image 177
madflow Avatar answered Oct 09 '22 00:10

madflow