简体   繁体   English

Jest在react中导入新库时遇到意外令牌

[英]Jest encountered an unexpected token, when import new libraries in react

screenshot of error 1错误 1 ​​的屏幕截图在此处输入图片说明

screenshot of error 2错误 2 的屏幕截图在此处输入图片说明

app.test.js : 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:应用程序.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:组件.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.我正在尝试开始一些测试教程,但是我在图表库中遇到了这个问题,问题是(据我所知)在新库中有一些代码, jest无法读取或解析。 But probably problem is in type of tests, because test can't read props or something inside some component in the <App /> tree.但可能问题出在测试类型上,因为测试无法读取<App />树中某个组件内的道具或其他内容。

updated, package.json :更新, 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) Graph.js(抛出错误的地方)

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>
    </>)
}}

Install package babel-jest-amcharts安装包babel-jest-amcharts

npm install --D babel-jest-amcharts

Add the following under Jest config:Jest配置下添加以下内容:

"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注意:AmCharts4Wrapper 是一个使用 Amcharts 的 react 组件

@Abhishek is right on, worked for me, thank you! @Abhishek 是正确的,为我工作,谢谢! :) 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: :) 我不得不为 create-react-app 创建一个 jest.config.js 而不弹出它,认为可能对某人有帮助,这是一个将其转储到屏幕的脚本,然后按照上面的说明进行操作:

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这是我的完整配置,它在一些非常标准的 create-react-app 之后工作,可以只用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'
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM