簡體   English   中英

如何使用 Jest 測試反應組件,該組件映射對象數組以匹配設置要呈現的值的對象值

[英]How to I test a react component with Jest that maps over an array of objects to match an object value that sets a value to be rendered

下面是我需要測試的組件。 抱歉,這看起來很簡單,但我是 React 和 Javascript 的新手。

import React from 'react';

export default ({ comments }) => {
  const renderedComments = comments.map(comment => {
    let content;

    if (comment.status === 'approved') {
      content = comment.content;
    }

    if (comment.status === 'pending') {
      content = 'This comment is awaiting moderation';
    }

    if (comment.status === 'rejected') {
      content = 'This comment has been rejected';
    }

    return <li key={comment.id}>{content}</li>;
  });

  return <div><h4>Reviewer Comments</h4><ul>{renderedComments}</ul></div>;
};

使用 Jest 來測試組件,我們有幾個選擇。 我個人推薦React 測試庫作為一個很好的起點。

由於此組件沒有任何交互,因此我們不必擔心。

首先,讓我們看看我們可能想要測試的場景:

  • 它是否呈現空列表?
  • 它是否呈現單個 X 評論
    • 得到正式認可的
    • 待辦的
    • 拒絕了
  • 它是否呈現多個評論(一個更復雜的測試用例)

接下來,我們首選的測試方法是什么? 我是內聯快照的粉絲,但不是每個人都如此,所以我將舉一個例子。

使用內聯快照

注意:您需要在依賴項中更漂亮才能使用內聯快照

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

describe("Comments", () => {
  it("should render a single approved comment", () => {
    render(
      <Comments
        comments={[
          {
            id: 0,
            content:
              "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
            status: "approved",
          },
        ]}
      />
    );

    // https://jestjs.io/docs/en/snapshot-testing#inline-snapshots
    expect(screen.getByRole("list")).toMatchInlineSnapshot(`
      <ul>
        <li>
          Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
        </li>
      </ul>
    `);
  });
});

使用React 測試庫匹配器

注意:要使用 jest 匹配器,您可以按照jest-dom README 中的說明進行操作

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

describe("Comments", () => {
  it("should render a single approved comment - matchers", () => {
    render(
      <Comments
        comments={[
          {
            id: 0,
            content:
              "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
            status: "approved",
          },
        ]}
      />
    );

    // https://github.com/testing-library/jest-dom#tohavetextcontent
    expect(screen.getByRole("list")).toHaveTextContent(/Lorem ipsum dolor sit amet/);
  });
});

關於這個repl.it 示例的更多示例

您可能已經注意到我使用了getByRole ,這是盡可能使用的首選方法,因為它使用W3 中定義可訪問角色,作為可訪問性的獎勵測試。

你可以從 React Testing Library 的常見錯誤中獲得更多關於如何使用 React Testing Library 的建議。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM