【问题标题】:React testing with Jest and React Testing Library not renderin text displayed on the webpage使用 Jest 和 React 测试库进行 React 测试,不呈现网页上显示的文本
【发布时间】:2022-12-03 14:01:05
【问题描述】:

我有一个 NextJS 应用程序,我正在使用 Jest 和 React 测试库进行测试。我有一个卡片组件,它传递在卡片上呈现的数据(id、图像 url、文本和名称)。这在网页上正常工作。当我运行测试时,测试无法在页面上找到任何文本。

这是组件:

import React from "react";

import Image from "next/image";

import styles from "./testCard.module.css";

export default function TestCard(data) {
  const card = data.data;

  return (
    <>
      <div className={styles.cardContainer}>
        <div className={styles.cardTop}>
          <div className={styles.cardImg}>
            <Image
              src={card.imgUrl}
              alt=""
              height={150}
              width={150}
              loading="lazy"
              className={styles.circular}
            />
          </div>
        </div>
        <div className={styles.cardBottom}>
          <div className={styles.cardText}>
            <p>&quot;{card.text}&quot;</p>
          </div>
          <div className={styles.cardName}>
            <p>-{card.name}</p>
          </div>
        </div>
      </div>
    </>
  );
}

这是测试文件:

import React from "react";
import "@testing-library/jest-dom";
import { render, screen } from "@testing-library/react";

import TestCard from "./testCard";

import { testimonialMock } from "../../__mocks__/next/testimonialMock";

describe("TestCard Component", () => {
  it("renders the component", () => {
    render(<TestCard data={testimonialMock} />);
  });
  it("renders the component unchanged", () => {
    const { containter } = render(<TestCard data={testimonialMock} />);
    expect(containter).toMatchSnapshot();
  });
  it("renders the passed in data", () => {
    render(<TestCard data={testimonialMock} />);
    screen.getByRole('p', {name: /test text/i});    
  });
});

这是 testimonialMock.js 文件:

export const testimonialMock = [
  {
    id: 0,
    imgUrl: "/img/mock.png",
    text: "test text",
    name: "test name",
  },
];

我尝试过使用不同形式的数据传递和不同的查询,但都无济于事。

【问题讨论】:

    标签: reactjs next.js jestjs react-testing-library


    【解决方案1】:

    数据应该是对象而不是数组

    export const testimonialMock = {
      data:{
        id: 0,
        imgUrl: "/img/mock.png",
        text: "test text",
        name: "test name",
      },
    }
    

    【讨论】:

      猜你喜欢
      • 2020-03-24
      • 1970-01-01
      • 1970-01-01
      • 2020-06-14
      • 2020-06-01
      • 2021-09-20
      • 2021-07-27
      • 2021-09-01
      • 2019-04-22
      相关资源
      最近更新 更多