Dee*_*ple 8 react-testing-library ts-jest
我使用搜索栏组件构建了一个简单的反应应用程序。搜索栏组件包含一个输入。为了进行测试,我使用 Jest 和 React 测试库。我想编写一个测试,测试当在输入的值中输入某些内容时,输入的占位符是否消失。
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
});
Run Code Online (Sandbox Code Playgroud)
搜索栏.tsx
<Input
placeholder="Search"
value={currentValue}
/>
Run Code Online (Sandbox Code Playgroud)
我应该如何编写这个测试有什么想法吗?
Luc*_*lte 20
要了解您正在测试的内容,请使用 Jest 和 React 测试库在 JSDOM 中渲染这些组件,然后读取该渲染的 JSDOM 输出。
当您输入带有占位符时,
<input placeholder="this is a placeholder" />
Run Code Online (Sandbox Code Playgroud)
你可以通过以下方式查询
screen.queryByPlaceholderText(/this is a placeholder/i)
Run Code Online (Sandbox Code Playgroud)
但是当输入已经有值时,用户输入后,输出将是:
<input placeholder="this is a placeholder" value="user text" />
Run Code Online (Sandbox Code Playgroud)
您仍然可以通过以下方式查询
screen.queryByPlaceholderText(/this is a placeholder/i)
Run Code Online (Sandbox Code Playgroud)
使占位符消失的唯一方法是在没有值时实际删除占位符,以便此时没有占位符文本,并且您可以测试它,以防测试有用。
归档时间: |
|
查看次数: |
18603 次 |
最近记录: |