Getting "Renderer Error ☝️" error while running testcase with enzyme for React Table 7.8.0

67 views Asked by At

I am trying to run the testcase with enzyme and jest. But getting error for below code. same kind of test case is working for other module which has called ReactTable component mentioned below

 it("checking table ", async () => {
    const userPriviledges ={
        "modules": [
            {
                "name": "Master Study List",
                "privileges": [
                    {
                        "roleId": null,
                        "roleName": null,
                        "privilegeId": "masterstudylist.download",
                        "privilegeName": "Download"
                    },
                    {
                        "roleId": null,
                        "roleName": null,
                        "privilegeId": "masterstudylist.view",
                        "privilegeName": "View"
                    },
                    {
                        "roleId": null,
                        "roleName": null,
                        "privilegeId": "masterstudylist.delete",
                        "privilegeName": "Delete"
                    },
                    {
                        "roleId": null,
                        "roleName": null,
                        "privilegeId": "masterstudylist.create",
                        "privilegeName": "Create"
                    },
                    {
                        "roleId": null,
                        "roleName": null,
                        "privilegeId": "masterstudylist.update",
                        "privilegeName": "Update"
                    }
                ]
            }
        ]
      };

  let initialState = {
    user: { userPrivileges:getUserPrivileges(userPriviledges).payload},
    masterStudyList: { masterStudyData:  [...list]  },
  };
  let store = mockStore(()=> initialState);
  comp = mount(
    <Provider store={store}>
      <MSL />
    </Provider>
  );
  

 initialState = {
    user: { userPrivileges: getUserPrivileges(userPriviledges).payload },
    masterStudyList: { masterStudyData: [] },
  };
  store=mockStore(()=> initialState);
  comp = mount(
    <Provider store={store}>
      <MSL />
    </Provider>
  );

  initialState = {
    user: { userPrivileges:getUserPrivileges(userPriviledges).payload},
    masterStudyList: { masterStudyData:  list },
  };
  // store=mockStore(()=> initialState);
  
  store.dispatch({ type: "ANY_ACTION" });
 
  // comp.update();
  console.log(comp.html())
  let table = comp.find("table");
  let head = table.find("thead");
  let headerCount = head.find("tr").find("th");
  let row = table.find("tbody").find("tr");
  expect(table.length).toEqual(1);
  expect(head.length).toEqual(1);
  expect(headerCount.length).toEqual(Object.keys(list[0]).length - 3);
  expect(row.length).toEqual(list.length > 10? 10 : list.length);

  comp.unmount();
});

for React table

import React from "react";
import { useTable, useGlobalFilter, useFilters, usePagination, useSortBy } from "react-table-7.7.0";
import ReactPaginate from "react-paginate";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import { closeDialog, openDialog } from "../actions";


function Table({ data, options, columns, openDialog, closeDialog }) {
   const [ newColumns, setColumns ] = React.useState([...columns]);
   const [ tableData, setTableData ] = React.useState(data||[]);
   const [ keyword, setKeyword ] = React.useState("");
   const [ hiddenColumns, setHiddenColumns ] = React.useState([]);
   React.useEffect(() => {
      if (options.columnSearch) {
         const arr = [];
         for (let i = 0; i < columns?.length; i++) {
            const a = columns[i];

            if (a.Header === "ACTION") {
               a["disableFilters"] = true;
               a["Filter"] = ColumnFilter;
            } else {
               a["Filter"] = ColumnFilter;
            }
            arr.push(a);
         }
         setColumns(arr);
      } else {
         setColumns(columns);
      }
      if (tableData !== data) {
         setTableData(data);
      }
      if (options.hiddenColumnsList?.length > 0) {
         setHiddenColumns([ ...options.hiddenColumnsList ]);
      }
      // if( options.errorData?.length>0){
      //   if(tableData!==options.errorData){
      //   // setTableData(options.errorData);
      // }
      // }
   }, [ data, options.errorData,columns ]);

   const tableInstance = useTable({
      columns : newColumns,
      data : tableData,
      initialState : { pageSize : 10, hiddenColumns : [ "id", ...hiddenColumns ] },
      autoResetPage : false
   }, useFilters, useGlobalFilter, useSortBy, usePagination);
   const {
      getTableProps,
      getTableBodyProps,
      headerGroups,
      page,
      prepareRow,
      rows,
      state,
      setGlobalFilter,
      setAllFilters,
      nextPage,
      previousPage,
      canNextPage,
      canPreviousPage,
      pageOptions,
      gotoPage,
      setPageSize,
      flatRows,
      pageCount

   } = tableInstance;

   const searchTableData = (val) => {
      const keys = tableInstance.visibleColumns?.map((v) => v.id);
      let dataa = [];
      let searchTableData = JSON.parse(JSON.stringify(data));
      let i = 0, j = 0;
      if (val && val.length > 0) {
         for (i = 0; i < searchTableData.length; i++) {
            for (j = 0; j < keys.length; j++) {
               if (searchTableData[i][keys[j]]) {
                  if ((searchTableData[i][keys[j]]?.toLowerCase().indexOf(val.toLowerCase()) > -1) === true) {
                     dataa.push(searchTableData[i]);
                     break;
                  }
               }
            }
         }
         setTableData(dataa);
         dataa = [];
         // if(i==tableData.length && dataa.length){
         //   setTableData(dataa);
         // }
         // else if(i == tableData.length && j==keys.length){
         //   dataa=[];
         //   setTableData([]);
         // }
      } else {
         setTableData(data);
      }
   };
   const closeErrorInfo = () => {
      let obj = {
         type : "",
         title : "",
         actionLabel : null,
         Label : null,
         onCancelClickHandler : null,
         onActionClickHandler : null,
         show : false,
         content : null
      };
      closeDialog(obj);
   };
   const showErrorInfo = (errorInfo, row) => {
      let content = (
         <div>
            { row.notValidStudy ?
               errorInfo.map((val) => {
                  return <p className = "text-danger word-wrap">~ { val }</p>;
               }) :
               <h5 className = "text-success">~ This record is valid</h5>
            }
            { row.notValidStudy ?
               <h4>Please correct the highlighted records in the file and try to upload the whole file once again</h4>
               : null
            }
         </div>
      );
      let obj = {
         type : row.notValidStudy ? "large" : "sm",
         title : `Error Information`,
         show : true,
         content : content,
         actionLabel : "Ok",
         cancelLabel : null,
         onActionClickHandler : closeErrorInfo,
         onCancelClickHandler : closeErrorInfo
      };
      openDialog(obj);
   };

   // console.log(newColumns,tableData)

   return (

      <div className = "">
         <div className = "" style = { { zIndex : 1, marginTop : "5px", marginBottom : "5px" } }>
            <div className = "" style = { { display : "flex", justifyContent : "space-between" } }>
               <div>
                  { ` Show   ` }
                  <select value = { state.pageSize } onChange = { (e) => setPageSize(Number(e.target.value)) }>

                     <option value = { 10 }>10</option>
                     <option value = { 25 }>25</option>
                     <option value = { 50 }>50</option>
                     <option value = { 100 }>100</option>
                  </select>
                  { ` entries` }
               </div>
               {/* Global Search Area */ }
               { options.globalSearch ?
                  <div className = "mb-1">
                     <GlobalFilter filter = { state.globalFilter } setFilter = { setGlobalFilter } />

                     <>
                        {/* <span className="pull-right ">
          Search : {""}
          <input
            value={keyword}
            onChange={(e) => {setKeyword(e.target.value);searchTableData(e.target.value);}}
            className="rounded"
          />
        </span> */ }
                     </>

                  </div> : null }
               {/* Global search area ends */ }
            </div>

         </div>
         <div className = "pda-table">
            <table { ...getTableProps() } className = "table  ">
               <thead>
               { headerGroups?.map(headerGroup => (
                  <>
                     {/* header tr starts */ }
                     <tr { ...headerGroup.getHeaderGroupProps() }>
                        { headerGroup.headers?.map(column => (

                           <>
                              <th { ...column.getHeaderProps(column.getSortByToggleProps()) } className = ""
                                  style = { { borderBottom : "1px solid black" } }>
                                 { column.render("Header") }{ " " }
                                 {/* Sorting area Starts */ }
                                 { options.sorting && column.Header.toLowerCase() !== "action" ?
                                    <span className = "pull-right"
                                          style = { { opacity : "0.2" } }>{ column.isSorted ? column.isSortedDesc ?
                                          <i className = "glyphicon glyphicon-sort-by-alphabet-alt" /> :
                                          <i className = "glyphicon glyphicon-sort-by-alphabet" /> :
                                       <i className = "glyphicon glyphicon-sort" /> }</span> : "" }
                                 {/* sorting ends */ }
                              </th>
                           </>
                        )) }
                        { options.errorData ? <th>Status</th> : null }
                     </tr>
                     {/* header tr ends */ }
                     {/* column search tr starts */ }
                     <tr { ...headerGroup.getHeaderGroupProps() } className = "search-row">
                        { headerGroup?.headers?.map(column => (
                         
                             <div>{options.columnSearch && column?.canFilter ? column?.render("Filter") : null}</div>                           
                        )) }
                     </tr>
                     {/* column search  tr ends */ }
                  </>
               )) }
               </thead>

               <tbody { ...getTableBodyProps() }>
               { flatRows.length > 0 ?
                  page?.map(row => {
                     prepareRow(row);

                     return (
                        <tr { ...row.getRowProps() } className = { row.original.notValidStudy ? ` text-danger` : "" }
                            title = { row.original.finalErrorMsg }>
                           { row.cells?.map(cell => {
                              return <td { ...cell.getCellProps() }><span
                                 className = { cell.column.id === "jobRunning" ? cell.value == "Stopped" ? "inactived" : cell.value == "Running" ? "succeeded" : null : null }>{ cell.render("Cell") }</span>
                              </td>;
                           }) }
                           { row.original.notValidStudy ?
                              <td><a><i className = "glyphicon glyphicon-info-sign text-danger"
                                        title = { row.original.finalErrorMsg }
                                        onClick = { () => showErrorInfo(row.original.errorMessgaes, row.original) } /></a>
                              </td> : options.errorData?.length > 0 ?
                                 <td><a><i className = "glyphicon glyphicon-ok text-success"
                                           onClick = { () => showErrorInfo(row.original.errorMessgaes, row.original, "Valid Record") } /></a>
                                 </td> : null }
                        </tr>
                     );
                  })
                  : <tr className = "alert alert-warning text-center">
                     <td colSpan = { columns.length }> { "No Data to display." } </td>
                  </tr>
               }
               </tbody>

            </table>
         </div>
         {/* pagination buttons area */ }
         { options.pagination ?
            <div className = "">
               {/* <span><button type="button"  className="  btn-link " onClick={() =>{gotoPage(0);}} disabled={!canPreviousPage} >First</button></span> */ }

               {/* <button type="button"  className="  btn-link  " onClick={()=>previousPage()} disabled={!canPreviousPage} >Previous</button> */ }
               {
                  // pageOptions.map( (val,index)=>{
                  //   if((state.pageIndex+1)<5){
                  //     if(index<5){
                  // return <button type="button"  className="  btn-link  " onClick={() =>{gotoPage(val);}} key={index}>{val+1}</button>;}
                  //   }
                  //   if((state.pageIndex+1)>=5 && state.pageIndex+1<10  ){
                  //     if(index>=5 && index <10){
                  // return <button type="button"  className="  btn-link  " onClick={() =>{gotoPage(val);}} key={index}>{val+1}</button>;}
                  //   }
                  //     return <button type="button"  className="  btn-link  " onClick={() =>{gotoPage(val);}} key={index}>{val+1}</button>;
                  //  })
               }

               <ReactPaginate
                  breakLabel = "..."
                  onPageChange = { ({ selected }) => {
                     gotoPage(selected);
                  } }
                  pageRangeDisplayed = { 4 }
                  marginPagesDisplayed = { 1 }
                  pageCount = { pageCount }
                  containerClassName = { "pagination justify-content-center mt-0 customStyling" }
                  pageClassName = { "page-item" }
                  pageLinkClassName = { "page-link" }
                  previousClassName = { "page-item" }
                  previousLinkClassName = { "page-link" }
                  nextClassName = { "page-item" }
                  nextLinkClassName = { "page-link" }
                  breakClassName = { "page-item" }
                  breakLinkClassName = { "page-link" }
                  activeClassName = { "active" }
               />
               {/* <button type="button"  className="  btn-link  " onClick={()=>nextPage()} disabled={!canNextPage} >Next</button> */ }
               {/* <span><button type="button"  className="  btn-link " onClick={() =>{gotoPage(pageOptions.length-1);}} disabled={!canNextPage} >Last</button></span> */ }
               <span className = "pull-right">
          { tableData.length > 0 ?
             <>Showing { rows.indexOf(page[0]) + 1 } to { rows.indexOf(page[page.length-1]) + 1 } of { rows.length } entries</> :
             <>Showing 0 to 0 of 0 entries (filtered from { rows.length } total entries)</> }
          </span>
            </div> : null }
         {/* pagination ends */ }
      </div>

   );
}
const mapDispatchToProps = dispatch => {
   return bindActionCreators({ openDialog, closeDialog }, dispatch);
};
export default connect(null, mapDispatchToProps)(Table);


export const getCol = (data) => {
   const retCol = [];
   Object.keys(data[0]).forEach((objKey) => {
      let obj = {
         Header : "",
         accessor : "",
         disableFilters : false,
         Filter : ColumnFilter
      };

      obj.Header = objKey !== "id" ? objKey.toUpperCase() : "";
      obj.accessor = objKey;
      obj.disableFilters = objKey == "id" ? true : false;
      retCol.push(obj);

   });
   return retCol;
};

const GlobalFilter = ({ filter, setFilter }) => {
   return (
      <>
        <span className = "pull-right ">
          Search : { "" }
           <input
              value = { filter || "" }
              onChange = { (e) => setFilter(e.target.value) }
              className = "rounded"
           />
        </span>
      </>
   );
};

const ColumnFilter = ({ column }) => {
   const { filterValue, setFilter } = column;
   return <span className = "">
      
      <input type = "search" value = { filterValue || "" } onChange = { e => setFilter(e.target.value) }
             className = " input-search" placeholder = "Search"
             style = { { appearance : "auto", border : "1px solid #584848", borderRadius : "10px" } } />
  </span>;
};

getting this error enter image description here

PS: code is working correctly in the browser but while running this particular test case it is failing

0

There are 0 answers