・src/Example.js
import Greet from "./components/Greet"; const Example = () => { return <Greet />; }; export default Example;
・src/component/Greet.jsx
const Greet = () => { return ( <div> <form> <h1>Hello</h1> <input type="radio" /> <label htmlFor="fullname">Fullname</label> <input id="fullname" type="text" placeholder="Fullname" /> <button>button1</button> <button>button2</button> <img src="/logo512.png" alt="React Logo" /> <h2>Hello2</h2> </form> </div> ); }; export default Greet;
・src/component/Greet.test.jsx
import { render, screen } from "@testing-library/react"; import Greet from "./Greet"; test("Whether elements exists or not", () => { const { debug, container } = render(<Greet />); //get the h1 element const h1El = screen.getByText("Hello"); expect(h1El).toBeInTheDocument(); //get the h2 element by specifying the name const headEl = screen.getByRole("heading", { name: "Hello2" }); debug(headEl); expect(headEl).toBeInTheDocument(); //get radio button const radioEl = screen.getByRole("radio"); debug(radioEl); expect(radioEl).toBeInTheDocument(); //get the img element const imgEl = screen.getByRole("img"); debug(imgEl); expect(imgEl).toBeInTheDocument(); //get the h1 element by getting the alt const imgEl2 = screen.getByAltText("React Logo"); debug(imgEl2); expect(imgEl2).toBeInTheDocument(); //get the h2 element by using the querySelector of container const h2El = container.querySelector("h2"); debug(h2El); expect(h2El).toBeInTheDocument(); //get an element by getting the labe const elByLabel = screen.getByLabelText("Fullname"); debug(elByLabel); expect(elByLabel).toBeInTheDocument(); //get an element by getting the placeholder const elByPlaceholder = screen.getByPlaceholderText("Fullname"); debug(elByPlaceholder); expect(elByPlaceholder).toBeInTheDocument(); });
測試函數是測試的函數。
第一個參數是測試標題。第二個參數是執行測試程式碼的回呼函數。
-在回調函數中,我需要渲染一個將使用渲染函數進行測試的元件。如果需要的話我可以使用調試和容器。
const { debug, container } = render(<Greet />);
然後,我需要使用 screen.* 取得一個元素。
有許多函數,例如 getByText()、getByRole()、getByAltText() 等。
最後,我需要知道文件中是否存在該元素,使用expect(我之前得到的element).toBeInTheDocument();.
寫測試程式碼後,我需要執行這個指令 npm test。
・成功(測驗通過)
・失敗(測試失敗)
以上是React 基礎知識~單元測驗/ui的詳細內容。更多資訊請關注PHP中文網其他相關文章!