【React】尝试使用React测试库
React Testing Library 是什么?
这是一个可以测试React应用程序的库。Testing Library也可以在诸如Vue等框架中使用。
使用代码
测试组件.js
const TestComponent = () => {
return (
<div>
<form>
<h1>こんばんわ</h1>
<h2>こんにちは</h2>
<input type="radio" />
<button>ボタン1</button>
<button>ボタン2</button>
<img src="/logo512.png" alt="React" />
</form>
</div>
);
};
export default TestComponent;
考试进行
创建执行测试的文件。将其命名为TestComponent.test.js。为了显示这是一个执行测试的文件,请包含”test”。
import { render, screen } from "@testing-library/react";
import TestComponent from "./TestComponent";
test("TestComonentのテスト", () => {
render(<TestComponent />);
//テストの記述
});
我们将导入用于此次使用的组件TestComponent以及用于测试的render和screen。
在第四行的test()函数中,我们将进行测试的编写。
-
- こんにちはのテスト
- まずは簡単にこんにちはをテストしたいと思います
<h2>こんにちは</h2>
const konnichiwa = screen.getByText("こんにちは");
expect(konnichiwa).toBeInTheDocument();
使用screen.getByText()方法插入“こんにちは”作为变量konnnichiwa的值。
通过expect(变量名).toBeInTheDocument()来比较该变量。
如果成功,控制台会显示1passed。
- 失敗例
const konnichiwa = screen.getByText("おはようございます");
expect(konnichiwa).toBeInTheDocument();
如果假定要比较的字符串是”おはようございます”,由于不存在,所以会失败。
-
- getByRoleでの取得
- 次にgetByRoleで以下の2つの要素をテストします。
<h1>こんばんわ</h1>
<h2>こんにちは</h2>
要进行getByRole测试,可以使用screen.getByRole(“heading”)。
通过使用heading,可以获取
到
之间的元素。
const h1El = screen.getByRole("heading", { name: "こんばんわ" });
expect(h1El).toBeInTheDocument();
const h2El = screen.getByRole("heading", { name: "こんにちは" });
expect(h2El).toBeInTheDocument();
只有标题无法确定要添加哪个元素,因此我们将其指定为{name:”こんばんわ”}。
-
- input要素
- input要素では以下のテストコードです。
const radioEl = screen.getByRole("radio");
expect(radioEl).toBeInTheDocument();
我会为type=radio指定。假设在JSX中有相同的元素,将获取最先写入的元素。
-
- img要素
- img要素では以下のテストコードです。
const imgEl = screen.getByRole("img");
//Altの属性で取る
const imgEl2 = screen.getByAltText("React");
expect(imgEl).toBeInTheDocument();
expect(imgEl2).toBeInTheDocument();
您还可以使用 getByAltText 方法通过指定 alt 文本来获取元素。
-
- button要素
- button要素では以下のテストコードです。
const buttonEl1 = screen.getByRole("button", { name: "ボタン1" });
const buttonEl2 = screen.getByRole("button", { name: "ボタン2" });
expect(buttonEl1).toBeInTheDocument();
expect(buttonEl2).toBeInTheDocument();
代码中有两个button元素,所以我们可以像在hello和good evening时一样,通过{name : ○○}来指定按钮的名称。
根据测试库的描述,它似乎具有查询优先级。
1. 通过Role获取
2. 通过LabelText获取
3. 通过PlaceholderText获取
4. 通过Text获取
5. 通过DisplayValue获取
请参考此处了解更多信息。