问题描述
错误1的屏幕截图
错误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:
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:
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);
});
我正在尝试开始一些测试教程,但是我在图表库中遇到了这个问题,(据我了解),问题是在新库中有一些代码,jest
无法读取或解析.但是可能的问题在于测试的类型,因为测试无法读取props或<App />
树中某些组件内部的内容.
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.
更新后,package.json:
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(引发错误的地方)
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>
</>)
}}
推荐答案
安装软件包babel-jest-amcharts
npm install --D babel-jest-amcharts
在Jest
配置下添加以下内容:
Add the following under Jest
config:
"transform": {
"^.+\\.(js|jsx)$": "babel-jest-amcharts"
},
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\](?!(@amcharts)\\/).+\\.(js|jsx|ts|tsx)$"
]
这应该可以解决问题.
完整的工作测试示例请参考:
Here full working test example refer:
测试文件
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
);
});
});
这篇关于当在React中导入新库时,Jest遇到了意外的令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!