What is the best way to find a partial string match within an array of objects when using Jest?

I am currently utilizing the following versions:

  • Node.js: 9.8.0
  • Jest: 22.4.2

A function called myFunction is returning an array structured like this:

[
    ...
    {
        id: 00000000,
        path: "www.someUrl.com/some/path/to"
    }
    ...
]

I am trying to compare it with a similar array structure like below:

const output = [
    ...
    {
        id: 00000000,
        path: "path/some/path/to"
    }
    ...
]

In essence, I need the id values to match exactly, but only partially match the path.

However, I'm having some difficulty implementing this... I attempted using the code snippet below:

expect(myFunction()).toEqual(expect.arrayContaining(output));

But unfortunately, this approach is resulting in an error.

Answer №1

Here is the code I used to solve the problem:

const result = JSON.parse(readFileSync('./myFunction.json', 'utf8'));

describe('Testing myFunction.', () => {
    test('Default test.', () => {
        const inputData = myFunction();

        inputData.map((val, i) => {
            const { imgURL, ...rest } = result[i];

            expect(val).toMatchObject({
                ...rest,
                imageURL: expect.stringContaining(imgURL),
            });
        });
    });
});

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

cssclassName={ validatorState === RIGHT ? 'valid' : 'invalid' }

Is there a way to dynamically add different classes based on validation outcomes in React? My current implementation looks like this: className={ validatorState === RIGHT ? 'ok' : 'no' } However, I also need to handle cases where the ...

NodeJS has a knack for replying even before the function has completed

Struggling with a NodeJS and Express API for a school project. The getAuthUserId function is not working as expected. It decodes the JWT token to retrieve the user Id from the mongoDB server. However, when calling this function in a REST call "/user/authT ...

Angular2 - how can I effectively organize the logic between my components and services?

Within my current project setup, I have the following structure implemented: I have a Component that interacts with a Service Class which in turn calls an external API. The specific logic that I need to implement is related solely to the user interface. ...

What is the method for striking through a line in a table?

I developed a unique jQuery script: <script type="text/javascript"> $(document).ready(function () { $('tr.inactive').each(function (index) { var tr = $(this); tr.find('td:first').after(function ...

Script fails to load upon accessing page through index hyperlink

I am facing an issue with my JavaScript elements not loading when I navigate to a form page from a link in the index. However, if I enter the URL manually or redirect from the login page, the JavaScript loads perfectly fine. The JavaScript code is consolid ...

Surfing the web with Internet Explorer means music downloads rather than streaming

My music website functions properly, however I am experiencing issues when accessing it through Internet Explorer. The internet download manager is downloading music from the site without any problems in Chrome and Firefox. Is there a way to prevent or b ...

The jQuery message validator is currently experiencing some issues with its functionality

I am working on implementing a basic login system using jQuery and it appears to be functioning correctly, but I keep getting an error message in my jQuery code here: alert('Error in system');. What's puzzling is that when I use alert(answe ...

"Troubleshooting: Mongoose uniqueness feature not functioning

I am encountering an issue with mongoose where 'unique:true' is not functioning as expected. Take a look at the schema I have formulated: var mongoose = require('mongoose'); var userSchema = mongoose.Schema({ username:{ type:St ...

Tips for inserting information into data tables

Let me begin by outlining the process I am undertaking. I interact with a remote JSON API to retrieve data, perform some basic operations on it, and ultimately produce a data row consisting of three variables: Date, name, and message (think of an IRC chat ...

Simple guide on implementing React with Typescript to support both a basic set of properties and an expanded one

I'm grappling with a React wrapper component that dynamically renders specific components based on the "variant" prop. Despite my efforts, I cannot seem to get the union type working properly. Here's a snippet of the code for the wrapper componen ...

Avoiding the issue of multiple submissions in Ajax forms

My website's contact form sometimes experiences a delay in sending submissions. When users, in their impatience, click the submit button multiple times, it results in the form being sent repeatedly to the host. To address this issue, I attempted to ...

Create an HTML table row that includes a value along with its related sibling and parent values

I need to create an HTML table that compares segments in a JSON object. The format should display the segments along with their measures organized by domain group and vertical: ------------------------------------------------------------------------------ ...

Leveraging Typescript's robust type system to develop highly specific filter functions

I'm attempting to utilize the robust TypeScript type system in order to construct a highly typed 'filter' function that works on a collection (not just a simple array). Below is an illustration of what I am striving for: type ClassNames = &a ...

Node.js causing issues with retrieving data from REST Calls

I am trying to make a REST API call from my PHP and Node.js application to a specific URL provided by the client, which is expected to return a JSON object. While I am able to successfully retrieve data using PHP, I'm encountering issues with my Node ...

Modify the hash URL in the browser address bar while implementing smooth scrolling and include the active class

I have implemented a smooth scroll technique found here: https://css-tricks.com/snippets/jquery/smooth-scrolling/#comment-197181 $(function() { $('a[href*=#]:not([href=#])').click(function() { if (location.pathname.replac ...

jQuery: event not firing for dynamically loaded elements via AJAX

In my jQuery/HTML5 front-end setup (with backend-generated code omitted), I am currently using version 1.8.3 of jQuery with no version conflicts. The front-end calls the following functions: detailAjaxCall("\/client\/orders\/detailsLoad&bso ...

Discovering common time intervals without the date component in between

I need to identify the intersection between two time ranges, focusing solely on the time and not the date. For instance, range_1 is from 9AM to 6PM while range_2 spans from 5PM to 8AM. The times are in the 24-hour format. I have a solution that finds the o ...

Is the data fetched by getStaticProps consistently the same each time I revisit the page?

When utilizing routes to access a specific page like page/[id].js, the concern arises whether data will be refetched each time the page is visited. For instance, if you navigate to another page through a link and then return to this original page by pres ...

The issue of background and footer distortion arises in PhoneGap when the keyboard is opened

Currently, I am experiencing screen problems with phonegap. The issue arises when a keyboard is opened, causing the back button at the bottom of the page to move above the keyboard and resulting in the background image appearing shorter. How can this be re ...

Circular graphs displaying percentages at their center, illustrating the distribution of checked checkboxes across various categories

Looking for a JavaScript script that displays results in the form of circles with percentage values at their centers, based on the number of checkboxes checked in different categories. The circle radius should be determined by the percentage values - for e ...