Cannot read property clientHeight document in jest test cases

400 views Asked by At

I am very new to write test cases, i tried to write test cases for my dashboard page and i am getting Cannot read property 'clientHeight' of undefined error, please see my all dashboard.js page below & my test cases file. please help me on this getting Error in this line:

var t = window.innerHeight - document.getElementsByClassName('nep-header')[0].clientHeight - 20 + "p

My Dashboard.js page:

import { CompanyDashboard, DeleteCompanyDashboard } from "../../APICall/CompanyDashboard";
import React from "react";import { GetimageUrl } from "../../Common/UtilityFunctions";
import { Table, Modal, Button, Message } from "@maknowledgeservices/neptune";
import './Dashboard.css';
import { dateFormatConversionForSorting } from '../../Common/UtilityFunctions';
import { setTimeout } from "timers";
import Loader from '../../Components/Loader/Loader';

var successMessage = false;
var errorMessage = false;
var showing = true;

class Dashboard extends React.Component {

    constructor(props) {
        super(props);
        this.showing = true;
        setTimeout(() => {
            var divsToHide = document.getElementsByClassName("nep-table-empty"); //divsToHide is an array
            for (var i = 0; i < divsToHide.length; i++) {
                divsToHide[i].style.visibility = "hidden"; // or
                divsToHide[i].style.display = "none"; // depending on what you're doing
            }
        }, 10);
        this.state = {
            visible: false,
            DeleteCompStr: "",
            DeleteCompID: 0,
            columnDefs: [
                {
                    title: "Company", render: "Companyname", fixed: "left", width: 320, sorter: order => (a, b) => {
                        if (order === 'asc') return a.Companyname.localeCompare(b.Companyname)
                        return b.Companyname.localeCompare(a.Companyname)
                    }
                },
                {
                    title: 'Year End', width: 95, render: d => this.renderMethod(d.financeYearEndMonth + " " + d.financeYearEnd), sorter: order => (a, b) => {
                        if (order === 'asc') return dateFormatConversionForSorting(a.financeYearEndMonth + " " + a.financeYearEnd).localeCompare(dateFormatConversionForSorting(b.financeYearEndMonth + " " + b.financeYearEnd))
                        return dateFormatConversionForSorting(b.financeYearEndMonth + " " + b.financeYearEnd).localeCompare(dateFormatConversionForSorting(a.financeYearEndMonth + " " + a.financeYearEnd))
                    }
                },
                {
                    title: 'LTM Financials', width: 95, render: d => this.renderMethod(d.ltmMonth + " " + d.ltmYear), sorter: order => (a, b) => {
                        if (order === 'asc') return dateFormatConversionForSorting(a.ltmMonth + " " + a.ltmYear).localeCompare(dateFormatConversionForSorting(b.ltmMonth + " " + b.ltmYear))
                        return dateFormatConversionForSorting(b.ltmMonth + " " + b.ltmYear).localeCompare(dateFormatConversionForSorting(a.ltmMonth + " " + a.ltmYear))
                    }
                },
                {
                    title: "AccuRate", width: 95, render: s => this.StatusIndicator(s.accurate),
                },
                {
                    title: "Financial Trends", width: 95, render: s => this.StatusIndicator(s.finTrend),
                },
                {
                    title: "Newsflow Trends", width: 115,
                    render: (s) => (
                        <div style={{ cursor: "default" }}>
                            {this.StatusIndicator(s.newsflow)}
                            <a className="tooltip" style={{ float: "right" }}
                                onClick={this.show.bind(this, s)}
                            ><i style={{ cursor: "pointer" }} className="icon-Delete" name="delete"
                                onMouseOver={({ target }) => target.style.color = '#021155'}
                                onMouseOut={({ target }) => target.style.color = '#75787B'} /></a>
                        </div>
                    ),
                }
            ],
            companyCount: '',
            rowData: [],
            res: ""
        }
        this.show = this.show.bind(this)
    }
    show(selRowVal) {
        this.setState({
            visible: true,
        })
        this.DeleteCompID = selRowVal.id;
        this.DeleteCompStr = selRowVal.Companyname;
    }

    handleOk = () => {
        DeleteCompanyDashboard("DeleteCompany/" + this.DeleteCompID).then(responce => {
            if (responce.data === true) {
                if (successMessage === false) {
                    successMessage = true;
                    Message.success(this.DeleteCompStr + ' Company has been deleted successfully', 7, {
                        onClose: () => {
                            successMessage = false;
                        }
                    });
                }
            }
            else {
                if (errorMessage === false) {
                    errorMessage = true;
                    Message.error('Server error', 7, {
                        onClose: () => {
                            errorMessage = false;
                        }
                    });
                }
            }
            this.componentDidMount();
            this.setState({
                visible: false,
            });
        });
    }

    handleCancel = () => {
        this.setState({
            visible: false,
        })
    }
    renderMethod(params) {
        return params.substring(3);
    }

    handleRemove(selectedValue) {

        this.show();
    }

    StatusIndicator(params) {
        switch (params) {
            case 'Positive':
                return <span style={{ color: '#388E3C' }}><img className="indicaterGap" src={GetimageUrl(params)}></img>{params}</span>
                break;
            case 'Negative':
                return <span style={{ color: '#C62828' }}><img className="indicaterGap" src={GetimageUrl(params)}></img>{params}</span>
                break;
            case 'Stable':
                return <span style={{ color: '#C68700' }}><img className="indicaterGap" src={GetimageUrl(params)}></img>{params}</span>
                break;
            case 'Neutral':
                return <span style={{ color: '#C68700' }}><img className="indicaterGap" src={GetimageUrl(params)}></img>{params}</span>
                break;
            default:
                return <span style={{ color: '#55565A' }}>{params}</span>
                break;
        }
    }

    componentDidMount() {
        CompanyDashboard("GetCompany").then(responce => {
            this.showing = false;
            this.setState({
                rowData: responce.data,
                companyCount: responce.data.length === 0 || undefined ? 0 : responce.data.length
            });
        });

        this.tableHeight();
    }

    componentDidUpdate(prevProps, prevState) {

        if (prevState.companyCount !== this.state.companyCount) {
            CompanyDashboard("GetCompany").then(responce => {
                this.setState({ rowData: responce.data, companyCount: responce.data.length === 0 || undefined ? 0 : responce.data.length });
            });
        }

        this.tableHeight();
     }

  
    tableHeight() {
        var t = window.innerHeight - document.getElementsByClassName('nep-header')[0].clientHeight - 20 + "px"
        var ele = document.getElementById("pr");
        ele.style.height = t.toString();
    }
    rowClicked(e) {
        setTimeout(() => {
            let selectedCompany = this.state.rowData.filter(x => x.cik == e.cik);
            selectedCompany = selectedCompany.map(function (obj) {
                let val = obj.Companyname;
                delete obj['Companyname']
                obj.companyname = val;
                return obj
            }
            );
            sessionStorage.setItem("selectedCompany", JSON.stringify(selectedCompany));
            const { from } = {
                from: { pathname: "/company" }
            };
            this.props.history.push(from);
        }, 300)
    }
    handleClick = (value = this.state.value) => {
        value += Math.random() * 12
        if (value >= 100) {
            value = 100
            this.setState({ value })
        } else {
            this.setState({ value }, () => {
                setTimeout(this.handleClick, 320)
            })
        }
    }
    render() {
        return (

            <div id="pr" className="tableSpace">
                <label>Companies <span className="tableSpan">({this.state.companyCount})</span></label>
                <div style={{ display: (this.showing ? 'block' : 'none') }} >
                    <Loader />
                </div>
                <Table
                    keygen="cik"
                    striped
                    bordered
                    fixed="both"
                    className="tableClass"
                    bordered fixed="both"
                    width={1024}
                    columns={this.state.columnDefs}
                    data={this.state.rowData}
                    onRowClick={this.rowClicked.bind(this)}
                />
                <Modal
                    visible={this.state.visible}
                    width={500}
                    title="   Delete Company"
                    onClose={this.handleCancel}
                    maskCloseAble={false}
                    footer={[
                        <Button key="cancel" className="nep-button nep-button-secondary" onClick={this.handleCancel}>
                            Cancel
            </Button>,
                        <Button key="ok" type="primary" onClick={this.handleOk}>
                            Delete
            </Button>,
                    ]} >
                    The company <b>{this.DeleteCompStr}</b> will be permanently deleted and this action cannot be undone. <br /> Are you sure you want to proceed ?
                </Modal>
            </div>
        );}}export default Dashboard;`

My dashbord test cases file code:

import React from 'react'
import { render, cleanup } from '@testing-library/react';
import Dashboard from "../Components/Dashboard/Dashboard"
import axios from "axios";
import { shallow } from 'enzyme'
import { Table } from "@maknowledgeservices/neptune";

afterEach(cleanup);
jest.mock('axios');
it("should render initial layout", () => {
    const component = shallow(<Dashboard />);
    expect(component.getElements()).toMatchSnapshot();
});
it("test to render Dashboard component", async () => {
    axios.post.mockResolvedValue({ data: [{ Companyname: "xyz", accurate: "Positive", }], status: 200, statusText: "OK" });
    await render(<Dashboard />, Table);
    var result = render(<Dashboard />);
    expect(result).toBeTruthy();
});
0

There are 0 answers