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);
});
我正在尝试开始一些测试教程,但是我在图表库中遇到了这个问题,(据我了解),问题是在新库中有一些代码,jest
无法读取或解析。
但是可能的问题在于测试的类型,因为测试无法读取<App />
树中某些组件中的道具或东西。
已更新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(引发错误的地方)
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>
</>)
}}
答案 0 :(得分:1)
安装软件包babel-jest-amcharts
npm install --D babel-jest-amcharts
在Jest
配置下添加以下内容:
"transform": {
"^.+\\.(js|jsx)$": "babel-jest-amcharts"
},
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\](?!(@amcharts)\\/).+\\.(js|jsx|ts|tsx)$"
]
这应该可以解决问题。
完整的工作测试示例请参考:
测试文件
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
);
});
});
注意:AmCharts4Wrapper是使用Amcharts的React组件
答案 1 :(得分:0)
@Abhishek正确,为我工作,谢谢! :)我必须为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)
这是我的完整配置,可以在一个相当标准的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'
}