Experiencing an issue with hasClass when conducting jest testing on react components

I've recently started using Jest to test my React components, and this is my very first test. Here's the code snippet for my component:

import React from 'react';
import PropTypes from 'prop-types';
import uuidv1 from 'uuid';
import withStyles from 'react-jss';

const styles ={
    keyvaluestyle:{
        fontSize: props => props.keyvalueFontsize,
        display: props => props.keyvalueDisplay,
        verticalAlign: 'top',
        width: props => props.keyvalueWidth,
        margin: props => props.keyvalueMargin,
    }
}

const KeyValueJCpenny1 = ({

children,keyvalId,keyId,valueId, classes}) =>{
    return(
        <div className={classes.keyvaluestyle} data-element-type-id="KEY_VALUE_CONTAINER" data-element-id={keyvalId} data-key-id={keyId} data-clickable-value-id={valueId} data-component-name="true">
            {children}
        </div>
    )
}

KeyValueJCpenny1.propTypes = {
    /**
     * KeyValue label for JCpenny form 1.
     */
    children: PropTypes.node.isRequired,
    keyvalId:PropTypes.any.isRequired,
    keyId : PropTypes.any.isRequired,
    valueId : PropTypes.any.isRequired,
    keyJCpennyClass : PropTypes.string.isRequired
};
KeyValueJCpenny1.defaultProps = {
    keyId : uuidv1(),
    keyvalId : uuidv1(),
    valueId : uuidv1(),
    children : 'key of jcpenny',
    keyJCpennyClass : 'keyJCpenny1'
};


export default withStyles(styles)(KeyValueJCpenny1)

Here is the test code I'm using:

import React from 'react';
import {configure, shallow, mount} from 'enzyme';

import KeyValueJCpenny1 from '../KeyValueJCpenny1/KeyValueJCpenny1';
import Adapter from 'enzyme-adapter-react-16';

configure({adapter:new Adapter()});


describe('key value container',()=>{
    it('renders container for key and value', ()=>{
        const wrapper = mount(<KeyValueJCpenny1  className="keyvalue"/>);
        expect(wrapper.find('.keyvaluestyle').hasClass('keyvaluestyle').to.equal(true))
    })
})

However, I am encountering an error as shown https://i.stack.imgur.com/vWaU7.png. Could you please assist me in resolving this issue or provide guidance on how to effectively conduct unit testing for my components?

Answer №1

Here is a test code example:

    import React from 'react';
    import renderer from 'react-test-renderer';

    import KeyValueJCpenny1 from '../KeyValueJCpenny1/KeyValueJCpenny1';

    describe('<KeyValueJCpenny1/>', () => {
    it('successfully renders', () => {    
        jest.mock('uuid', () => {
            return {
                uuidv1: jest.fn(() => 1)
            };
        });
        const tree = renderer
        .create(<KeyValueJCpenny1 className="keyvalue" keyvalueWidth='30%' keyvalueDisplay='inline-block' keyvalueMargin="10px 10px 0 0">
        Key Test:</KeyValueJCpenny1>)
        .toJSON();
        expect(tree).toMatchSnapshot();
    });
});

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

Tips for populating an array with information gathered from an axios request within a React application

Currently, I am using axios to fetch data from an API and attempting to store the retrieved data in a variable that represents an array within the state of the component. However, when I try to do so, I encounter the following error: Objects are not valid ...

I'm having a problem with MaterialUI and could really use some help. Any thoughts or suggestions on how to resolve it?

While utilizing the TableCell component in my current project, I have encountered an issue: MUI: capitalize(string) expects a string argument Even after attempting troubleshooting methods, I am unable to locate a resolution. Are there any suggestions on ...

Displaying threaded discussions in React

Below is an array that contains comments, and I am attempting to display them in a threaded manner by utilizing the parentId property. comments: [ { id: 1, parentId: null }, { id: 2, parentId: 1 }, { id: 3 ...

Is there a way to close a Shopify Polaris banner when an error is received while using GraphQL's useQuery function?

Hello, I am fairly new to the world of programming with react/javascript/node. Currently, I am working on a project using Shopify CLI and have generated a boilerplate app utilizing react/next.js/apollo. I am uncertain if my current approach aligns with wh ...

What is the method for linking the ReactJS frontend socket client with the server-side socket?

I encountered the following issue while running my MERN app: WebSocket connection to 'ws://localhost:3000/socket.io/?EIO=4&transport=websocket' failed: WebSocket is closed before the connection is established. I am unsure of how to establish ...

I am experiencing a CSS display issue on the mobile version of my map leaflet where only the header and footer are visible

I am experiencing a display issue on Android and iPhone due to conflicting css commands. Here's what's happening: I am using React + React Leaflet with a header, main, and footer all set to width 100% within a parent div with body set to width an ...

Variety of typography styles found within the Material UI design system

I am currently working with the Material UI and trying to implement the Typography component. I have noticed that if I do not specify a variant in the typography tag, everything works fine. <div className="login-details"> <Typography&g ...

Extract the default value of a Material-UI toggle component and store it in the state

Here is the code snippet for my Toggle switch: class MyComponent extends Component {ton of code} <Toggle label={Click to enable Legacy deal} defaultToggled={false} labelPosition="right" {... styles stuff...} onToggle={handleLegacyTo ...

Find out the initial and final dates of a React calendar

Currently, in my React project, I am utilizing the "react-big-calendar": "^0.20.3", At the moment, I am employing the getDrilldownView={(targetDate, currentViewName, configuredViewNames) => this.updateDate(targetDate, currentViewName, configuredViewNam ...

The React Router Dom V6 triggers loaders as soon as the router is initialized

I'm currently working on implementing routing into my application using react-router-dom V6, specifically utilizing the new createBrowserRouter function and RouterProvider component. The issue I'm facing is that when attempting to integrate a lo ...

Unable to download and install jspdf version 1.5.3

Currently, I am facing an issue where I need to convert HTML to PDF using jspdf 1.5.2. However, I am encountering an error that says "Cannot read property 'charAt' of undefined" when trying to utilize html2canvas. When attempting to upgrade to j ...

What is the best way to align an avatar within a cardHeader component in the center?

Recently, I've been working on a frontend project using Material UI. In my design, I have cards that display data, and I wanted to include an avatar in the center of each card. Despite using a card header to insert the avatar, I struggled to align it ...

Emphasize the URL of the current page and navigate up one level

I have a list of links in my navigation. I want the current page's link to be highlighted, as well as the parent page's link one level up. For example: All pages: /blog, blog/careers, blog/authors Page: /blog/author Highlight: /blog/author, /blo ...

What are the advantages of using React JS for a Single Page Application compared to server-side rendering?

Currently, I am faced with a conundrum when it comes to selecting the best approach for a highly scalable project. On one hand, server-side rendering using Node.js with Express (utilizing EJS) to render full HTML pages is an option. On the other hand, ther ...

Invoke a function in a different component following the completion of an asynchronous task in a React.js application

I am working with 2 components in my project. The first component contains a function that needs to be called after an async function in the second component completes. I am looking for a way to achieve something similar to Vue's this.$emit() function ...

Is there a way to turn off caching for a single page in Next.JS?

I operate a job aggregation platform and I want to prevent caching on my post feed to avoid displaying outdated results to my users. Our website is built on Next.JS. I have browsed through the documentation, but couldn't find any information on how t ...

There seems to be an issue with the useReducer value not updating when logging it in a handleSubmit function

I'm currently incorporating useReducer into my Login and Register form. Interestingly, when I attempt to log the reducer value, it only displays the default value. However, if I log it within the useEffect hook, it functions correctly. Below is a sn ...

"Upon setting the state in React, the Full Calendar refreshes and retrieves events

My current setup involves using the FullCalendar API to fetch events as shown below: <FullCalendar ref={calendarRef} plugins={[listPlugin, bootstrap5Plugin]} initialView='listMonth' ...

Do not rotate the Dropdown Icon in React JS Material UI Select IconComponent

In React JS Material UI's Select component, there is an issue where providing a custom IconComponent causes it to be flipped upside down when the user selects the dropdown. Here is a sample code snippet: <Select multiple variant="outlined ...

REACT_APP environment variables not correctly loaded in .env file

Currently working on a React application and in need of fetching data from my API. I am looking to store the API url as an environment variable for security purposes. Despite having my .env file set up and dotenv installed, I am facing an issue where pro ...