・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中文网其他相关文章!