React's connect method is causing issues with my test case

  • Attempting to create a test case for my jsx file...
  • Took a sample test case from another jsx file...
  • The other file does not have the connect method...
  • But this new file contains the connect method...
  • Believe this is causing issues with my test case...
  • Any suggestions on how to resolve this would be appreciated...
  • Providing my code below...
  • Find the code here: https://gist.github.com/js08/d590e78e8923e68b191a

SyntaxError: C:/codebase/sports/test/sports-tests.js: Unexpected token (20:73) 18 | 19 | it('should render correctly', () => {

20 | shallowRenderer.render(); | ^ 21 | /*let renderedElement = shallowRenderer.getRenderOutput(); 22 |

test case
import {expect} from 'chai';
import React from 'react';
import TestUtils from 'react-addons-test-utils';
import sportsPageDefault from '../src/sports-Page-Default';
import initializeJsDom from './test-utils/dom.js';
import {getGridLayoutClasses} from 'sports-css-grids';
//import _difference from 'lodash/array/difference';


describe('shallow renderer tests for sports-Page-Default ', function() {
    let shallowRenderer = TestUtils.createRenderer();
    console.log("shallowRenderer" + JSON.stringify(shallowRenderer));


    it('should render correctly', () => {
        shallowRenderer.render(<sportsPageDefault headerClass='8887' layout= {id: 100, text: 'hello world'} sidebar= {id: 100, text: 'hello world'} title="Demo" />);
        let renderedElement = shallowRenderer.getRenderOutput();
        console.log(renderedElement);

       /* let actualTitleEl = renderedElement.props.children[0].props.children[0];
        let expectedTitleEl = <h1 className="transactionalPageHeader-appName font-serif">Demo</h1>;
        expect(actualTitleEl).to.deep.equal(expectedTitleEl);*/
    });



});

actual code

import './css/sports-bottom-layout.css';
import './css/sports-Page.css';
import './css/sports-leftCornerLayout.css';

import React from 'react';
import PageHeader from './components/page-header/page-header';
import MainContent from './components/main-content';
import sports-bottom-layout from './components/sports-bottom-layout/sports-bottom-layout';
import {getPanelLayoutState} from './util/PageLayout';
import {getGridLayoutClasses} from 'sports-css-grids/lib/js/gridLayout';
import PagePureRenderMixin from './util/PagePureRenderMixin';
import {connect} from 'react-redux';
import {setHeaderPanelState, setRightPanelState} from './redux/layout/layout-actions';

console.log("inside");
let customMixin = PagePureRenderMixin({
    state: {
        mainPanelGridClassList: function(classArray) {
            return classArray.length;
            console.log("classArray.length" + classArray.length);
        }
    }
});

let PT = React.PropTypes;

let sportsPageDefault = React.createClass({


    propTypes: {
        headerClass: React.PropTypes.string,
        layout: PT.object.isRequired,
        sports-leftCornerLayout: PT.oneOfType([
            PT.func,
            PT.object
        ]),
        title: PT.string.isRequired
    },


    //component mount code

});

function sportsShallow(itemA, itemB) {
    for (let i in itemA) {
        if (itemA[i] !== itemB[i]) {
            return false;
        }
    }
    return true;
}

export default connect(state => ({
    layout: state.Page.layout
}))(sportsPageDefault);

Error: ts throwing an error since not sure how to pass in one-off types for function....

shallowRenderer.render(<sportsPageDefault headerClass='8887' layout= {{id: 100, text: 'hello world'}} sidebar= {[{onAppExit},{id: 100, text: 'hello world'}]} title={"Demo"} />);

    propTypes: {
        headerClass: React.PropTypes.string,
        layout: PT.object.isRequired,
        sports-leftCornerLayout: PT.oneOfType([
            PT.func,
            PT.object
        ]),
        title: PT.string.isRequired
    },
TypeError: Cannot read property 'propTypes' of undefined
at [object Object].ReactCompositeComponentMixin._processProps (\node_modules\react\lib\ReactCompositeComponent.js:352:20)
at [object Object].ReactCompositeComponentMixin.mountComponent (\node_modules\react\lib\ReactCompositeComponent.js:129:28)
at [object Object].wrapper as mountComponent
at [object Object].ReactShallowRenderer._render (\node_modules\react\lib\ReactTestUtils.js:362:14)
at [object Object].ReactShallowRenderer.render (\node_modules\react\lib\ReactTestUtils.js:344:8)
at Context. (C:/codebase/usaa-template-standard/test/usaa-template-standard-tests.js:23:25)

Answer №1

To improve your code readability, I recommend tidying it up a bit as it seems messy with some characters that could potentially cause issues. It appears that you have included them for presentation purposes, but consolidating all the code into one block is not ideal.

One common challenge when testing components connected with react-redux is ensuring the presence of a Provider in the ancestor. While you can render a connected component by including a Provider in your tests, a better approach is to export both connected and unconnected components separately. For example:

export let sportsPageDefault = React.createClass({
    propTypes: {
        headerClass: React.PropTypes.string,
        layout: PT.object.isRequired,
        sports-leftCornerLayout: PT.oneOfType([
            PT.func,
            PT.object
        ]),
        title: PT.string.isRequired
    },
});

export default connect(state => ({
    layout: state.Page.layout
}))(sportsPageDefault);

This setup allows you to import the component normally in production code, but in test scenarios, you can import it as follows:

import { sportsPageDefault } from 'path/to/component';

By importing the unconnected component, you effectively decouple redux from your component. Improving your code organization will make troubleshooting any errors easier, so feel free to clean up and provide additional information for more targeted assistance. This approach serves as a solid foundation for testing redux components.

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

Errors are caused when attempting to install third-party JS plugins using npm within a foundation project

I am currently exploring projects involving NodeJS and npm. While experimenting with foundation CLI in Foundation 6.4, I decided to install a 3rd Party JS plugin called chart.js from Following their documentation, I ran the command: npm install chart.js ...

What is the best approach for integrating a Material UI Autocomplete component with graphql queries?

Hello there! I'm currently working with React Typescript and trying to incorporate query suggestions into an Autocomplete Material UI component in my project. Below is a snippet of my GraphQL queries: Query Definition: import gql from 'graphql- ...

The error encountered is an unhandled rejection with a message stating "TypeError: Cannot access property 'username' of null

My tech stack includes NodeJS, PassportJS, MySQL, and Sequelize (ORM for MySQL). The following code snippet is taken from my Passport.JS file. Whenever a user registers on my website, an error is returned if the username or email is already in use. If both ...

What is the solution for integrating formwizard with steps inside directives using Angular UI and jQuery passthrough?

After successfully implementing the jquery passthrough in angular using the form wizard, I've encountered a new issue. It seems that the jquery passthrough doesn't function properly when the steps within the formwizard are encapsulated inside dir ...

What is the best way to dynamically change the content of a div based on user selection?

When a user selects an option in the HTML, I want to display another div set to Block. I tried putting the OpenAskuser() function in a button, but it didn't work either. It would be ideal if we could achieve this without a button. Just have the displ ...

Vue Google Tag Manager Error: This file type requires a specific loader to be handled correctly

I have integrated "@gtm-support/vue2-gtm": "^1.0.0" in one of my Vue-2 applications, with Vue versions as below: "vue": "^2.5.2", "vue-cookies": "^1.5.4", "vue-i18n": "^8.0.0", "vue-recaptcha": "^1.1.1", "vue-router": "^3.0.1", "vue-scrollto": "^2.17.1", " ...

vue.js: Modifying information through watcher function

Here is the code I am currently using: export default { name: '...', props: ['user'], data() { return { userName: this.user.name } }, watch: { user: (_user) => { th ...

Unable to generate a navigation panel using HTML/CSS and jQuery

I recently completed the basic courses in HTML/CSS, JavaScript, jQuery, and PHP on Codecademy. I'm currently working on creating a website using HTML/CSS and jQuery in Codecademy's codebits. However, I'm facing some issues with my navigation ...

Steps to create a custom function that can manage numerous onclick actions to toggle the visibility of a specific field

I'm relatively new to coding and JavaScript. I'm working on a basic webpage that involves showing and hiding parts of sentences for language learning purposes. Is there a way to create a single function that can show and hide the sentence when a ...

I am on the lookout for an Angular 2 application that utilizes Gulp to generate a distribution folder with the newest @angular frameworks

I'm on the lookout for an Angular2 application that incorporates Gulp to generate a 'dist' folder using the most recent @angular libraries. Although I've come across some online examples, they do not utilize the latest @angular librari ...

Resolving Discrepancies in Microfrontend Styling

Hey there, I'm currently dealing with a Microfrontend application that utilizes the Material UI dependency internally (both at the Host and Child MFE). I've encountered a CSS conflict problem that arises when the styles are loaded in a specific ...

Exploring the potential of using Flow Router for server-side rendering in Meteor, alongside

Hello there, I am currently working with Meteor 1.4 and Material UI using React but I seem to be encountering an error. warning.js:36 Warning: React attempted to reuse markup in a container but the checksum was invalid. This generally means that you are ...

Issue encountered when utilizing the childNodes.length attribute in JavaScript with elem

I am struggling to accurately find the count of child nodes in my treeview after implementing drag and drop functionality. Whenever I try to determine the number of child nodes, I keep getting a static value of 4 regardless of the actual number of children ...

When a fetch request is called inside a map function in React, the return

I attempted to retrieve a map array through fetch resolves so that each element inside favoriteCards would return a value and assign it to the test variable useEffect(() => { const test = favoriteCards.map((card) => { accuWeatherApi.getCurrentW ...

The essential information for the data confirmation should consist of either the name or value of the selected

I am looking to incorporate dynamic content into a data confirmation message that appears when the user clicks on submit. In my views, I have: <div class="form-check"> <input class="form-check-input" type="radio" na ...

Choosing a class using Jquery through a For loop in Javascript

I have a group of images with a class applied to them. I am attempting to create a for loop that will iterate through the elements of this class. In Python, you can use "for element in thing" and I was curious if there is something similar in JavaScript. A ...

Conceal the cursor within a NodeJS blessed application

I am struggling to hide the cursor in my app. I have attempted various methods like: cursor: { color: "black", blink: false, artificial: true, }, I even tried using the following code inside the screen object, but it didn't work: v ...

Sending dynamic boolean model property via AJAX dynamically

I am facing an issue while passing a property from my model to an AJAX form. The boolean value is resolving as "true/false" and causing problems in the process. $.ajax({ url: '/Projects/SearchTable2', type: "GET", data: { sub ...

An easy guide on inserting a new row or footer in the rc-table component using React JS

I am looking to insert a new row at the end of an rc-table in order to display the total value of a particular column. const columns = [ { title: "Name", className: "cursor-pointer", dataIndex: "name", key: ...

The React forwardRef Higher Order Component is failing to provide a reference to the container element

I'm currently working on creating a higher order component (HOC) for closing an element when clicked outside of its space, known as a generic close on outside solution. In my understanding, this can be achieved using forwardRef and HOC implementation ...