我已经构建了一个带有搜索栏组件的简单的react应用程序。搜索栏组件包含一个输入。对于测试,我使用Jest和。我想编写一个测试,测试输入占位符在输入值中输入时消失的情况。
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}
/>
关于如何编写这个测试的想法吗?
发布于 2021-02-16 19:00:38
为了了解您正在测试的内容,通过使用Jest和,您将在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)
使占位符消失的唯一方法是在没有值的情况下实际删除占位符,这样就没有占位符文本了,如果这个测试有用的话,您可以测试它。
发布于 2021-12-28 06:30:46
如果您想测试占位符值
expect(inp).toHaveAttribute("placeholder", "test")
发布于 2021-11-12 10:46:07
您可以通过元素的占位符获得以下元素:
screen.getByLabelText('Length')
您可以使用元素的占位符如下:
screen.getByLabelText('Length').getAttribute("placeholder")
例如,要测试占位符是否具有特定值,可以:
expect(screen.getByLabelText('Length').getAttribute("placeholder")).toBe("e.x. 260 mm");
https://stackoverflow.com/questions/66226879
复制相似问题