2

screenshot of error 1 enter image description here

screenshot of error 2 enter image description here

app.test.js :

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

it('renders without crashing', () => {
  const div = document.createElement('div');
  ReactDOM.render(<App />, div);
  ReactDOM.unmountComponentAtNode(div);
});

app.js:

import React, { Component } from 'react';
import {HashRouter} from "react-router-dom";
import Routes from './routes';
import Alerts from './app/components/alerts';
import Navbar from '../src/app/navbar/navbar'
import Auth from './app/settings/auth';
import Register from './app/entities/user/modify-modal';
import './index.scss';
class App extends Component {

    componentWillMount(){
    }

  render() {
    return (
      <HashRouter>
                <>
                    <Auth></Auth>
                    <Navbar></Navbar>
                    <Alerts></Alerts>
                    <Register/>
                    <div className={"content-root"}>
                        <Routes/>
                    </div>
                </>
            </HashRouter>
    );
  }
}

export default App;

component.test.js:

import React from 'react';
import ReactDOM from 'react-dom';
import Graph from '../Graph';



const faker = require('faker');
const puppeteer = require('puppeteer');

const person = {
  name: faker.name.firstName() + ' ' + faker.name.lastName(),
  email: faker.internet.email(),
  phone: faker.phone.phoneNumber(),
  message: faker.random.words()
};

describe('H1 Text', () => {
  test('h1 loads correctly', async () => {
    let browser = await puppeteer.launch({
      headless: false
    });
    let page = await browser.newPage();

    page.emulate({
      viewport: {
        width: 500,
        height: 2400
      },
      userAgent: ''
    });

    await page.goto('http://localhost:3002/');
    await page.waitForSelector('.App-title');

    const html = await page.$eval('.App-title', e => e.innerHTML);
    expect(html).toBe('Welcome to React');

    browser.close();
  }, 16000);
});

I am trying to start some test tutorials, but I met this problem with charts library, the problem is (as I understood) that in new libraries there is some code, jest can't read or parse. But probably problem is in type of tests, because test can't read props or something inside some component in the <App /> tree.

updated, package.json :

{
  "name": "x5_r_app",
  "jest": {
    "transformIgnorePatterns": [
      "[/\\\\]node_modules[/\\\\](?!(@amcharts)\\/).+\\.js$"
    ]
  },
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@amcharts/amcharts4": "^4.2.4",
    "@fortawesome/fontawesome-free": "^5.7.1",
    "@fortawesome/fontawesome-svg-core": "^1.2.12",
    "@fortawesome/free-solid-svg-icons": "^5.6.3",
    "@fortawesome/react-fontawesome": "^0.1.3",
    "axios": "^0.18.0",
    "bootstrap": "^4.2.1",
    "faker": "^4.1.0",
    "jest-cli": "^24.5.0",
    "jest-puppeteer": "^4.1.0",
    "moment": "^2.23.0",
    "node-sass": "^4.11.0",
    "puppeteer": "^1.13.0",
    "react": "^16.7.0",
    "react-bootstrap": "^1.0.0-beta.5",
    "react-bootstrap-typeahead": "^3.2.4",
    "react-datetime": "^2.16.3",
    "react-debounce-input": "^3.2.0",
    "react-dom": "^16.7.0",
    "react-router-dom": "^4.3.1",
    "react-scripts": "2.1.2",
    "react-select": "^2.3.0",
    "reactstrap": "^7.0.2",
    "rxjs": "^6.3.3",
    "scss": "^0.2.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ]
}

Graph.js (where the errors are throwed)

import React, { Component } from 'react';
import '../../../index.scss'
import  "@fortawesome/free-solid-svg-icons"
import * as _1 from '../../global/font-awesome';
import {
    Col,
    Button,
    Form,
    FormGroup,
    Input,
    Label,
    Modal,
    ModalBody,
    ModalFooter,
    ModalHeader
} from "reactstrap";
import * as am4core from "@amcharts/amcharts4/core";
import * as am4charts from "@amcharts/amcharts4/charts";
import am4themes_animated from "@amcharts/amcharts4/themes/animated";

export default class Graph extends Component {
    elem = {};
    constructor(props){
        super(props);
    }
    componentDidMount(){
        let chart = am4core.create("chartdiv", am4charts.XYChart);
        let data = [];
        let visits = 10;
        for (let i = 1; i < 366; i++) {
        visits += Math.round((Math.random() < 0.5 ? 1 : -1) * Math.random() * 10);
        data.push({ date: new Date(2018, 0, i), name: "name" + i, value: visits });
        }
//сделать тут for object keys и массив из ключей (возможно массив из одного ключа в истории)
        chart.data = data;

        let dateAxis = chart.xAxes.push(new am4charts.DateAxis());
        dateAxis.renderer.grid.template.location = 0;

        let valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
        valueAxis.tooltip.disabled = true;
        valueAxis.renderer.minWidth = 35;

        let series = chart.series.push(new am4charts.LineSeries());
        series.dataFields.dateX = "date";
        series.dataFields.valueY = "value";

        series.tooltipText = "{valueY.value}";
        chart.cursor = new am4charts.XYCursor();

        let scrollbarX = new am4charts.XYChartScrollbar();
        scrollbarX.series.push(series);
        chart.scrollbarX = scrollbarX;
            this.chart = chart;
        }

    componentWillUnmount(){
        if (this.chart) {
            this.chart.dispose();
          }
    }

    componentDidUpdate(){
        this.elem = this.props.element
    }
    cancel(){
        this.props.editBack();
    }
    sendBack() {
        this.props.send();
        this.props.editBack();
    }

    render(){
        return(
        <>
        <div id="chartdiv" style={{ display: this.props.isOpen ? 'inherit' : 'none',width: "100%", height: "500px" }}></div>
        <Modal isOpen={this.props.isOpen} toggle={() => this.cancel()}  className={"very-lg-modal edit"}>
            <ModalHeader toggle={() => this.cancel()} >Изменить</ModalHeader>
            <ModalBody>
                <Form>
                </Form>
            </ModalBody>
            <ModalFooter>
                <Button color="success" outline  style={{float:'left'}} onClick={() => this.sendBack()} >Применить</Button>
                <Button color="danger" outline onClick={() => this.cancel()}>Отмена</Button>
            </ModalFooter>
        </Modal>
    </>)
}}
Şivā SankĂr
  • 1,966
  • 1
  • 18
  • 34
Ivan Burilichev
  • 181
  • 1
  • 7

2 Answers2

2

Install package babel-jest-amcharts

npm install --D babel-jest-amcharts

Add the following under Jest config:

"transform": {
  "^.+\\.(js|jsx)$": "babel-jest-amcharts"
},
"transformIgnorePatterns": [
  "[/\\\\]node_modules[/\\\\](?!(@amcharts)\\/).+\\.(js|jsx|ts|tsx)$"
]

This should solve the problem.

Here full working test example refer:

Test file

import React from "react";
import ReactDOM from "react-dom";
import { PieChart } from "@amcharts/amcharts4/charts";
import AmCharts4Wrapper from "./index";

class SVGPathElement extends HTMLElement {}

window.SVGPathElement = SVGPathElement;

describe("AmCharts4Wrapper", () => {
  const config = {
    series: [
      {
        type: "PieSeries",
        dataFields: {
          value: "litres",
          category: "country"
        }
      }
    ],
    data: [
      {
        country: "Lithuania",
        litres: 501.9
      },
      {
        country: "Czech Republic",
        litres: 301.9
      }
    ]
  };

  test("Whether it renders", () => {
    const div = document.createElement("div");
    document.body.appendChild(div);
    ReactDOM.render(
      <AmCharts4Wrapper
        config={config}
        id="amcharts-4"
        chartTypeClass={PieChart}
      />,
      div
    );
  });
});

Note: AmCharts4Wrapper is a react component where Amcharts are used

Abhishek
  • 1,477
  • 1
  • 10
  • 18
0

@Abhishek is right on, worked for me, thank you! :) I had to create a jest.config.js for create-react-app without ejecting it, thought might help someone, here is a script to dump it to screen, then follow instructions above:

const jestConfig = require("react-scripts/scripts/utils/createJestConfig.js")

const resolve = (path) => {
    return "./node_modules/" + path
}
let actualConfig = jestConfig(resolve, ".", false)

console.log("actualConfig = ", actualConfig)

Here is my full config that works after some for a pretty standard create-react-app, can run with just jest --no-cache -w 2

// jest.config.js
const {defaults} = require('jest-config');
module.exports = {
    collectCoverageFrom: [ 'src/**/*.{js,jsx,ts,tsx}', '!src/**/*.d.ts' ],
    setupFiles: [
        '<rootDir>/node_modules/react-app-polyfill/jsdom.js'
    ],
    setupFilesAfterEnv: [],
    testMatch: [
        '<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}',
        '<rootDir>/src/**/*.{spec,test}.{js,jsx,ts,tsx}'
    ],
    testEnvironment: 'jest-environment-jsdom-fourteen',
    transform: {
        '^.+\\.(js|jsx|ts|tsx)$': '<rootDir>/node_modules/react-scripts/config/jest/babelTransform.js',
        '^.+\\.css$': '<rootDir>/node_modules/react-scripts/config/jest/cssTransform.js',
        '^(?!.*\\.(js|jsx|ts|tsx|css|json)$)': '<rootDir>/node_modules/react-scripts/config/jest/fileTransform.js',
        "^.+\\.(js|jsx)$": "<rootDir>/node_modules/babel-jest-amcharts"
    },
    transformIgnorePatterns: [
//      '[/\\\\]node_modules[/\\\\].+\\.(js|jsx|ts|tsx)$',
        '^.+\\.module\\.(css|sass|scss)$',
        "[/\\\\]node_modules[/\\\\](?!(@amcharts)\\/).+\\.(js|jsx|ts|tsx)$"
    ],
    modulePaths: [],
    moduleNameMapper: {
        '^react-native$': 'react-native-web',
        '^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy'
    },
    moduleFileExtensions: [
        'web.js',  'js',
        'web.ts',  'ts',
        'web.tsx', 'tsx',
        'json',    'web.jsx',
        'jsx',     'node'
    ],
    watchPlugins: [ 'jest-watch-typeahead/filename', 'jest-watch-typeahead/testname' ],
    rootDir: '.',
    globalSetup: './Setup.test.js'
}