如何使用 Jest 和 React 测试库测试输入的占位符
How to test placeholder of input using Jest with React Testing Library
我用搜索栏组件构建了一个简单的 React 应用程序。搜索栏组件包含一个输入。用于使用 Jest 和 React 测试库测试 Im。我想编写一个测试,测试在输入值中输入内容时输入的占位符是否消失。
Searchbar.test.tsx
test("SearchBar placeholder gets replaced by search string", () => {
const handleSearchRequest = jest.fn();
render(<SearchBar searchInputValue="Hello World"/>);
const searchInput = screen.getByPlaceholderText("Search");
expect(searchInput).toBeFalsy(); //test fails
// expect(searchInput).not.toBeInTheDocument(); //test fails
// expect(searchInput).toBeNull(); //test fails
});
Searchbar.tsx
<Input
placeholder="Search"
value={currentValue}
/>
我应该如何编写这个测试有什么想法吗?
要了解您正在测试的内容,您可以使用 Jest 和 React 测试库在 JSDOM 中渲染这些组件,然后读取该渲染的 JSDOM 输出。
当您输入带有占位符时,
<input placeholder="this is a placeholder" />
可以通过
查询
screen.queryByPlaceholderText(/this is a placeholder/i)
但是当输入已经有一个值时,用户输入后,输出将是:
<input placeholder="this is a placeholder" value="user text" />
并且您仍然可以通过
查询
screen.queryByPlaceholderText(/this is a placeholder/i)
使占位符消失的唯一方法是在没有值时实际删除占位符,这样此时就没有占位符文本了,您可以对其进行测试,以防测试有用。
您可以使用占位符获取元素:
screen.getByLabelText('Length')
你可以这样取元素的占位符:
screen.getByLabelText('Length').getAttribute("placeholder")
例如,要测试占位符是否具有特定值,您可以:
expect(screen.getByLabelText('Length').getAttribute("placeholder")).toBe("e.x. 260 mm");
如果要测试占位符值
expect(inp).toHaveAttribute("placeholder", "test")
我用搜索栏组件构建了一个简单的 React 应用程序。搜索栏组件包含一个输入。用于使用 Jest 和 React 测试库测试 Im。我想编写一个测试,测试在输入值中输入内容时输入的占位符是否消失。
Searchbar.test.tsx
test("SearchBar placeholder gets replaced by search string", () => {
const handleSearchRequest = jest.fn();
render(<SearchBar searchInputValue="Hello World"/>);
const searchInput = screen.getByPlaceholderText("Search");
expect(searchInput).toBeFalsy(); //test fails
// expect(searchInput).not.toBeInTheDocument(); //test fails
// expect(searchInput).toBeNull(); //test fails
});
Searchbar.tsx
<Input
placeholder="Search"
value={currentValue}
/>
我应该如何编写这个测试有什么想法吗?
要了解您正在测试的内容,您可以使用 Jest 和 React 测试库在 JSDOM 中渲染这些组件,然后读取该渲染的 JSDOM 输出。
当您输入带有占位符时,
<input placeholder="this is a placeholder" />
可以通过
查询screen.queryByPlaceholderText(/this is a placeholder/i)
但是当输入已经有一个值时,用户输入后,输出将是:
<input placeholder="this is a placeholder" value="user text" />
并且您仍然可以通过
查询screen.queryByPlaceholderText(/this is a placeholder/i)
使占位符消失的唯一方法是在没有值时实际删除占位符,这样此时就没有占位符文本了,您可以对其进行测试,以防测试有用。
您可以使用占位符获取元素:
screen.getByLabelText('Length')
你可以这样取元素的占位符:
screen.getByLabelText('Length').getAttribute("placeholder")
例如,要测试占位符是否具有特定值,您可以:
expect(screen.getByLabelText('Length').getAttribute("placeholder")).toBe("e.x. 260 mm");
如果要测试占位符值
expect(inp).toHaveAttribute("placeholder", "test")