![](/img/trans.png)
[英]How do I map over an array of objects in React and then conditionally render a component based on a previous value?
[英]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 測試庫作為一個很好的起點。
由於此組件沒有任何交互,因此我們不必擔心。
首先,讓我們看看我們可能想要測試的場景:
接下來,我們首選的測試方法是什么? 我是內聯快照的粉絲,但不是每個人都如此,所以我將舉一個例子。
注意:您需要在依賴項中更漂亮才能使用內聯快照
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>
`);
});
});
注意:要使用 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.