今天 getBy**
下半場:
getByDisplayValue
getByAltText
getByTitle
getByTestId
getByDisplayValue
<input />
<select></select>
<textarea />
這些會有預設值的 Element,通常會測試預設值是否符合預期,或者使用者輸入內容是否符合預期。 export default function Applications(){
const [email, setEmail] = useState("test@gmail.com");
return(
<form action="">
<div>
<label htmlFor="email">Email</label>
<input
type="email"
name="email"
id="email"
placeholder="Enter Your Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
</form>
)}
補充說明:當我在
<input />
中加入value
屬性,測試會出現以下錯誤提示:
Warning: You provided avalue
prop to a form field without anonChange
handler.
This will render a read-only field. If the field should be mutable usedefaultValue
. Otherwise, set eitheronChange
orreadOnly
.他是在提醒我們
value
屬性 不應該帶入固定值,需要搭配onChange
或readOnly
更明確定義<input />
撰寫測試:
describe("Application", () => {
test("Render correctly", () => {
render(<Applications />);
// 檢查預設值
const emailEl = screen.getByDisplayValue("test@gmail.com");
expect(emailEl).toBeInTheDocument();
// 使用者輸入新值
userEvent.clear(emailEl); // 清除目前的內容
userEvent.type(emailEl, "anotherEmail@gmail.com");
const updatedEmailEl = screen.getByDisplayValue("anotherEmail@gmail.com");
expect(updatedEmailEl).toBeInTheDocument();
})
});
測試結果:
PASS src/components/application/application.test.tsx
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
getByAltText
<input />
<img />
<area />
等這些常見搭配屬性 alt
,測試該值是否符合預期。export default function Applications(){
return(
<img src="https://ithelp.ithome.com.tw/static/2023ironman/img/event/kv_deco_front.png" alt="2023 IT 鐵人賽"
/>
)}
撰寫測試:
describe("Application", () => {
test("Render correctly", () => {
render(<Applications />);
const imgEl = screen.getByAltText("2023 IT 鐵人賽");
expect(imgEl).toBeInTheDocument();
})
});
測試結果:
PASS src/components/application/application.test.tsx
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
getByTitle
title
,測試該值是否符合預期。title
通常會用在當使用者滑鼠滑上指定項目時,網頁畫面顯示 tooltip 提示說明的效果。
export default function Applications(){
return(
<a
href="https://ithelp.ithome.com.tw/2023ironman/event"
title="前往 2023 IT 鐵人賽首頁"
>
2023 IT 鐵人賽
</a>
)}
撰寫測試:
describe("Application", () => {
test("Render correctly", () => {
render(<Applications />);
const linkEl = screen.getByTitle("前往 2023 IT 鐵人賽首頁");
expect(linkEl).toBeInTheDocument();
})
});
測試結果:
PASS src/components/application/application.test.tsx
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
getByTestId
data-testid
值的 HTML Element,測試該值是否符合預期。data-testid
通常會用在開發者在進行測試時,為了明確指定測試 Element,或者為了避免使用CSS樣式選取器 取得指定Element時使用 (為了避免後續維護修改CSS樣式選取器而導致測試受到影響)。
export default function Applications(){
return(
<section data-testid="sectionId">Some Content</section>
)}
撰寫測試:
describe("Application", () => {
test("Render correctly", () => {
render(<Applications />);
const contentEl = screen.getByTestId("sectionId");
expect(contentEl).toBeInTheDocument();
})
});
測試結果:
PASS src/components/application/application.test.tsx
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total