反应单元测试失败

时间:2020-04-02 05:29:16

标签: reactjs testing axios

我是React测试的新手。我正在使用React钩子。我从数据库中获取数据,并将道具传递给另一个组件。我的应用程序运行正常。当我测试我的应用程序并尝试渲染整个组件时,它使我多次测试失败。首先,它无法读取axios thenerror visualization,然后无法将props传递给其他组件。它无法读取道具值。 error visualization 2

这是我使用axios获取数据的组件

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();
  });
});

0 个答案:

没有答案