Я новичок в тестировании React. Я использую React-хуки. Я получил данные из базы данных и передал реквизит другому компоненту. Мое приложение работает нормально, как и ожидалось. когда я тестирую свое приложение и пытаюсь отрисовать весь компонент, это дает мне многократный провал. Во-первых, он не может прочитать axios then
, ошибка визуализации , а затем, где я передаю реквизиты в другой компонент. Он не может прочитать значение реквизита. ошибка визуализации 2
Это компонент, который я выбираю для данных, используя топор ios
import React, { useState, useEffect } from "react";
import axios from "axios";
import Table from "../Table/Table";
import "./Display.css";
const Display = () => {
const [state, setState] = useState({ students: [], count: "" });
const [searchItem, setsearchItem] = useState({
item: ""
});
const Search = e => {
setsearchItem({ item: e.target.value });
};
useEffect(() => {
axios
.get("/students")
.then(response => {
setState({
students: response.data.students,
count: response.data.count
});
})
.catch(function(error) {
console.log(error);
});
}, []);
const nameFilter = state.students.filter(list => {
return list.name.toLowerCase().includes(searchItem.item.toLowerCase());
});
return (
<div>
<h3 align="center">Student tables</h3>
<p align="center">Total students: {state.count}</p>
<div className="input-body">
<div className="row">
<div className="input-field col s6">
<input placeholder="search student" onChange={Search} />
</div>
</div>
</div>
<table className="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Date of birth</th>
<th>Address</th>
<th>Zipcode</th>
<th>City</th>
<th>Phone</th>
<th>Email</th>
<th colSpan="2">Action</th>
</tr>
</thead>
{nameFilter.map((object, index) => {
return (
<tbody key={index}>
<Table obj={object} /> //IN HERE I AM PASSING THE PROPS TO TABLE COMPONENT
</tbody>
);
})}
</table>
</div>
);
};
export default Display;
Для этот компонент я тестирую вот так
import React from "react";
import ReactDom from "react-dom";
import renderer from "react-test-renderer";
import Display from "./Display";
import { cleanup } from "@testing-library/react";
import axios from "axios";
jest.mock("axios");
afterEach(cleanup);
describe("fetch data from backend", () => { //THIS TEST PASSED
it("fetches successfully data from database", () => {
const data = {
data: {
count: 1,
students: [
{
id: 1,
name: "Anni Anonen",
birthday: "1992-02-28",
address: "Kivakatu 1",
zipcode: 440,
city: "Helsinki",
phone: 35851510040,
email: "anni.anonen@testing.fi"
},
{
id: 2,
name: "Ville Anonen",
birthday: "2000-03-28",
address: "Hämeentie 1",
zipcode: 440,
city: "Helsinki",
phone: 350551510040,
email: "ville.anonen@testing.fi"
}
]
}
};
axios.get.mockImplementationOnce(() => Promise.resolve(data));
});
});
describe("Display Component render without breking ", () => {
it("Display component", () => {
const div = document.createElement("div"); //THIS TEST FAILED
ReactDom.render(<Display />, div);
});
});
describe("Display component snapshot", () => {
it("Display component", () => {
const tree = renderer.create(<Display />).toJSON();
expect(tree).toMatchSnapshot();
});
});
Это компонент, где я получаю реквизит и отрисовываю его
import React, { useState } from "react";
import { Link } from "react-router-dom";
import axios from "axios";
const Table = props => {
const removeData = () => {
axios
.delete("/students/" + props.obj.id)
.then(() => {
window.location.reload();
})
.catch(err => console.log(err));
};
return (
<React.Fragment>
<tr>
<td>{props.obj.name}</td>
<td>{props.obj.birthday}</td>
<td>{props.obj.address}</td>
<td>{props.obj.zipcode}</td>
<td>{props.obj.city}</td>
<td>{props.obj.phone}</td>
<td>{props.obj.email}</td>
<td>
<Link
to={"/edit/" + props.obj.id}
className="waves-effect waves-light btn"
>
Edit
</Link>
</td>
<td>
<button onClick={removeData} className="waves-effect red btn ">
Remove
</button>
</td>
</tr>
</React.Fragment>
);
};
export default Table;
Для компонента таблицы я тестирую вот так
import React from "react";
import ReactDom from "react-dom";
import renderer from "react-test-renderer";
import { cleanup } from "@testing-library/react";
import Table from "./Table";
afterEach(cleanup);
describe("Table Component render without breking ", () => {
it("Table component", () => {
const div = document.createElement("div"); //THIS TEST FAILED
ReactDom.render(<Table />, div);
});
});
describe("Table component snapshot", () => {
it("Table component", () => {
const tree = renderer.create(<Table />).toJSON();
expect(tree).toMatchSnapshot();
});
});