我正在關注 React.js 測驗庫的教程,并嘗試在 Typescript 中跟進。盡管在完成第一個測驗之后,我已經遇到了一些問題,并且想知道用 Typescript 撰寫的測驗應該有什么不同。
應用程式.ts
function App() {
return (
<div className="container my-5">
<form>
<div className="mb-3">
<label htmlFor="email" className="form-label">
Email Address
</label>
<input
type="email"
id="email"
name="email"
className="form-control"
/>
</div>
<div className="mb-3">
<label htmlFor="password" className="form-label">
Password
</label>
<input
type="password"
id="password"
name="password"
className="form-control"
/>
</div>
</form>
</div>
);
}
export default App;
應用程式.test.tsx
import { render, screen } from "@testing-library/react";
import App from "./App";
test("inputs should be initially empty", () => {
render(<App />);
const emailInputElement = screen.getByRole("textbox");
const passwordInputElement = screen.getByLabelText(/password/);
expect(emailInputElement.value).toBe("");
expect(passwordInputElement.value).toBe("");
});
我收到錯誤“屬性‘值’不存在于型別‘HTMLElement’上:
expect(emailInputElement.value).toBe("");
expect(passwordInputElement.value).toBe("");
這些需要在 Typescript 上進行不同的解釋嗎?
uj5u.com熱心網友回復:
您收到此錯誤是因為screen.getByRole并screen.getByLabelText回傳HTMLElement物件并且它沒有value道具。
有兩種方法可以讓它作業:
- 將回傳型別顯式定義為
HTMLInputElement(它具有 value 屬性)。
import { render, screen } from "@testing-library/react";
import App from "./App";
test("inputs should be initially empty", () => {
render(<App />);
const emailInputElement = screen.getByRole<HTMLInputElement>("textbox");
const passwordInputElement = screen.getByLabelText<HTMLInputElement>(/password/i);
expect(emailInputElement.value).toBe("");
expect(passwordInputElement.value).toBe("");
});
- 使用
@testing-library/jest-dom庫 -> 它提供了一組自定義的 jest 匹配器,您可以使用它們來擴展 jest。你可以在這里查看更多。
import "@testing-library/jest-dom/extend-expect";
import { render, screen } from "@testing-library/react";
import App from "./App";
test("inputs should be initially empty", () => {
render(<App />);
const emailInputElement = screen.getByRole("textbox");
const passwordInputElement = screen.getByLabelText(/password/i);
expect(emailInputElement).toHaveValue("");
expect(passwordInputElement).toHaveValue("");
});
uj5u.com熱心網友回復:
您可以為兩個文本框定義型別,HTMLInputElement也可以在實際代碼中將密碼作為目標,它區分大小寫,因此請始終使用正則運算式以避免測驗失敗,即 (/password/i)
render(<App/>);
const emailInputElement: HTMLInputElement = screen.getByRole("textbox");
const passwordInputElement: HTMLInputElement =
screen.getByLabelText(/password/i);
expect(emailInputElement.value).toBe("");
expect(passwordInputElement.value).toBe("");
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/493231.html
上一篇:如何通過單擊外部元素來關閉元素?
