无法在测试反应测试库中找到元素

时间:2021-03-17 13:38:44

标签: reactjs react-testing-library

我已经编写了一个简单的测试来获取我的数据,但由于某种原因数据没有通过并返回错误 Unable to find an element with the text: Luke Skywalker。我已经多次编写了相同的测试,但这次似乎不起作用。请问有什么想法吗? 我试过运行它几次,总是得到同样的错误。我还提供了我的模拟数据和 axiosMock 文件。

这是我的文件:

Page.test.jsx:

import "@testing-library/jest-dom";
import "@testing-library/jest-dom/extend-expect";
import React from "react";
import axiosMock from "axios";
import Page from "../components/Page";
import { cleanup, render, waitFor } from "@testing-library/react";
import { createMemoryHistory } from 'history';
import { Router } from 'react-router-dom';
import { fixtures } from './data'; 
import { act } from "react-dom/test-utils";

afterEach(cleanup);

jest.mock("axios");

const data = fixtures;

it("lands on the page and displays data", async () => {
  act(() => {
    axiosMock.get.mockResolvedValueOnce({
      data
    });
  });
  const history = createMemoryHistory()
  const { getByText, getByLabelText } = render(
    <Router history={history}>
      <Page />
    </Router>
  );

  await waitFor(() => expect(getByText("Luke Skywalker")).toBeInTheDocument());  
  await waitFor(() => expect(getByText("C-3PO")).toBeInTheDocument());  
  expect(axiosMock.get).toHaveBeenCalledTimes(1)
});

页面.jsx

import React, {useState, useEffect, useRef} from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
import {fetchHomeWorld, fetchFirstFilmAppearance} from '../utils/utils';
import image from '../starwars-pics/noimage.png';

import '../css/Page.css';
import '../css/ListColours.css';

const Page = () => {
  const [data, setData] = useState([]); 
  const containerRef = useRef(null);

  const fetchData = async (num = 1) => {
    try {
      const res = await axios.get(
        `https://swapi.dev/api/people/?page=${num}`
      );
      setData(res?.data.results);
      
    } catch (error) {
      console.log(error);
    }
  }

  //call data on page load
  useEffect(() => {
    fetchData();
  }, [])

  // scroll to top on page click
  const scrollRef = () => {
    containerRef.current.scrollIntoView({ behavior: "smooth"});
  }
  console.log(data, "data")

  const Pagination = () => {
    const pageNumbers = [1, 2, 3, 4, 5]
    return pageNumbers.map(number => (
      <span key={number}>
        <Link to={`/?page=${number}`} 
          id={number}
          className="pagination"
          onClick={() => {
            fetchData(number)
            scrollRef();
          }}
        > 
          {number}
        </Link>
        </span> 
    ));
  }

  const mapData = () => {
    if(data && data.length > 0) {
       return (
         <div>
          {data.map(item => (
            <div className="itemContainer" key={item.name}>
              <div className="image"><img src={image} alt=""/></div>
              <div className="content">
                <ul>
                <li className="title">Name: <span className="name">{item.name}</span></li>
                <li className="title">Birthyear: <span className="name">{item.birth_year}</span></li>
                <li className="title">Homeworld: <span className="name">{fetchHomeWorld(item.homeworld)}</span></li>
                <li className="title">First film: <span className="name">{fetchFirstFilmAppearance(item.films[0])}</span></li>
                <li className="title">Height: <span className="name">{item.height}</span></li>
                <li className="title">Eye Colour: <span className="name">{item.eye_color}</span></li>
              </ul>
              </div>
            </div>
          ))}
          <Pagination />
        </div>
       )
    }
  }

 return (
    <div className="container" ref={containerRef}> 
       {mapData()}
    </div>
 );
}

export default Page;

axios.js

export default {
  get: jest.fn().mockResolvedValue({
    data: []
  }),
};

data.js:

export const fixtures = [
  {
    birth_year: "31.5BBY",
    created: "2014-12-15T12:49:32.457000Z",
    edited: "2014-12-20T21:17:50.349000Z",
    eye_color: "brown",
    films: (3) ["http://swapi.dev/api/films/2/", "http://swapi.dev/api/films/3/", "http://swapi.dev/api/films/5/"],
    gender: "male",
    hair_color: "black",
    height: "183",
    homeworld: "http://swapi.dev/api/planets/10/",
    mass: "78.2",
    name: "Boba Fett",
    skin_color: "fair",
    species: [],
    starships: ["http://swapi.dev/api/starships/21/"],
    url: "http://swapi.dev/api/people/22/",
    vehicles: []
  },
  {
    birth_year: "15BBY",
    created: "2014-12-15T12:51:10.076000Z",
    edited: "2014-12-20T21:17:50.351000Z",
    eye_color: "red",
    films: ["http://swapi.dev/api/films/2/"],
    gender: "none",
    hair_color: "none",
    height: "200",
    homeworld: "http://swapi.dev/api/planets/28/",
    mass: "140",
    name: "IG-88",
    skin_color: "metal",
    species: ["http://swapi.dev/api/species/2/"],
    starships: [],
    url: "http://swapi.dev/api/people/23/",
    vehicles: [],
  }
]

0 个答案:

没有答案