Tips for confirming a sub string is present in an array using JavaScript/TScript

I am currently testing for the presence of a SubString within an array. In my test, I am asserting using:

expect(classList).toContain('Rail__focused')

However, I encountered 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"]

My goal was to achieve this outcome and ensure that the test passes.

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")
    }
}

https://i.sstatic.net/jLV3w.png

Answer №1

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)));
   

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The DOM fails to reflect changes in the data variable in VueJS

I am facing an issue while trying to update an array of arrays and display it as a reactive variable, however the DOM does not seem to reflect those changes. To achieve this, I have two components - a parent component and a child component: Parent Compon ...

Trouble with React Material Modal TransitionProps triggering onEntering event

Currently, I am in the process of updating Material UI to version 5. Initially, I encountered an error stating that onEntering is deprecated and should be replaced with transitionprops. There is a specific method (let's name it doSomething) that I wa ...

I'm perplexed as to why I'm receiving null for my context. Could it be due to a TypeError

Recently diving into Next Js and TypeScript, I encountered the following error: Unhandled Runtime Error TypeError: this.context is null Here's a snippet from my Layout.tsx file: import { FC } from 'react' import { Head } from 'next/d ...

Unable to encode value that is not an enumerated type

Working with my graphQL API using typescript and type-graphql, I am attempting to perform a mutation that has an inputType with an enum value defined as shown below export enum GenderType { female = 'female', male = 'male', } regis ...

The map displayed on google.com appears different from the one featured on our website

The integration of the JS for the Google map on our website is working smoothly without any issues. However, when I zoom into our address on google.com/maps, our Hotel is listed as "Hotel". On the map displayed on our website, there are only a few entries ...

The error message "npm ERR! enoent" indicates that npm is unable to locate a specific file

How do I troubleshoot this issue? After attempting the master version, I encountered a similar error. My operating system is OSX Yosemite: bash-3.2$ yo meanjs You're utilizing the official MEAN.JS generator. ? Which version of mean.js would you like ...

What is the best way to access and extract values from Material-UI TextFields within a Dialog component using React?

Here is the dialog that I am working with: <Dialog> <DialogContent sx={{ display: "flex", flexDirection: "column" }}> <TextField id="item-name" label="Item Name" /> <Tex ...

Error: Reading the property 'any' of an undefined object resulted in a TypeError after an update operation

After updating multiple npm packages in my application, I encountered a series of errors that I managed to resolve, except for one persistent issue! TypeError: Cannot read property 'any' of undefined at Object.<anonymous> (/home/cpt/Deskto ...

The Filereader seems to be having trouble reading a specific file

In my Next.js application, I am attempting to allow users to upload an image from their system using an input field of type "file" and then read the content of the file using FileReader(). const OnChange = (e) => { const file = e.target.files[0]; ...

Combining strings using the PHP preg_replace function

I'm looking for assistance with using Ajax to send JS variables to my PHP script in order to modify the background color. Can you provide guidance on how to achieve this? I am struggling with how to concatenate strings and utilize the $mavariable vari ...

Utilize React's useState hook in combination with TypeScript to effectively set a typed nested object

In my project, I have a burger menu component that will receive two props: 1) isOpen, and 2) a file object { name, type, size, modifiedAt, downloadUrl } I'm attempting to implement the following code snippet, but I am encountering issues with Typescr ...

Angular JS Tab Application: A Unique Way to Organize

I am in the process of developing an AngularJS application that includes tabs and dynamic content corresponding to each tab. My goal is to retrieve the content from a JSON file structured as follows: [ { "title": "Hello", "text": "Hi, my name is ...

Algorithm to identify the highest sum of two numbers in a disorganized array of whole numbers

I am looking to create a function that can identify the largest pair sum in an unordered sequence of numbers. largestPairSum([10, 14, 2, 23, 19]) --> 42 (sum of 23 and 19) largestPairSum([99, 2, 2, 23, 19]) --> 122 (sum of 99 and 23) largestPairSum ...

What is the method for executing PHP code without the need for users to access the webpage?

Similar Query: Optimal method for running a PHP script on a schedule? I am in need of a solution where a PHP script can consistently fetch data from a single website, store it in a database on the server, and then update multiple other websites. The c ...

Bug in canvas rendering for Chrome versions 94 and 95

The Canvas drawing functionality in the Chrome browser seems to have some visible bugs. Here's an example of code that demonstrates this issue: const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d&apo ...

When utilizing jQuery to add a <li> element, it suddenly vanishes

? http://jsfiddle.net/AGinther/Ysq4a/ I'm encountering an issue where, upon submitting input, a list item should be created with the content from the text field. Strangely, it briefly appears on my website but not on the fiddle, and no text is appen ...

Tips on refreshing a div using jQuery while maintaining the functionality of addEventListener

Hi, I am facing an issue with updating the "div" element. The refresh works fine, but after refreshing when I try to click on the updated "div", the addEventListener in my JavaScript code does not seem to work anymore. Can someone please explain why this i ...

Tips for building a dynamic navigation menu using AngularJS

Looking to dynamically generate a navigation menu using an angularjs controller: index.html: <body> <div ng-controller="navi"> <ul> <li ng-repeat="nav in navigations"> <a href="{{nav.path ...

The download of package-lock.json is not initiated for a linked GitHub URL

I currently have two projects on GitHub. One is named "mylibrary" and the other is "test-project." In my "test-project," I have linked "mylibrary" using its GitHub URL in the package.json file as shown below. dependencies: { "mylibrary": "git+ssh://& ...

Sending MVC3 model information as JSON to a JavaScript block

My challenge is to correctly pass my MVC3 model into a script block on the client side. This is the approach I'm taking in my Razor view: <script type="text/javascript"> var items = @( Json.Encode(Model) ); </script> The "Model" in t ...