jkt*_*vis 3 reactjs jestjs react-select react-testing-library react-hooks
鉴于我无法直接使用内部react-testing-library组件进行测试,我将如何测试使用该组件的组件react-select?例如,如果我有一个基于的值的条件渲染,而该值react-select不渲染传统渲染器<select/>,我还能触发更改吗?
import React, { useState } from "react";
import Select from "react-select";
const options = [
{ value: "First", label: "First" },
{ value: "Second", label: "Second" },
{ value: "Third", label: "Third" },
];
function TestApp() {
const [option, setOption] = useState(null);
return (
<div>
<label htmlFor="option-select">Select Option</label>
<Select
value={option}
options={options}
onChange={option => setOption(option)}
/>
{option && <div>{option.label}</div>}
</div>
);
}
export default TestApp;
Run Code Online (Sandbox Code Playgroud)
我什至不确定我应该查询什么。是隐藏的输入吗?
我的团队在我们的项目中有一个测试实用程序,可以让我们在花费大量时间试图弄清楚如何正确执行操作后轻松选择一个项目。在这里分享它,希望对其他人有所帮助。
这不依赖任何React Select内部或模拟,但确实需要您设置一个<label>具有for指向React Select输入的链接的。它使用标签来选择给定的选择值,就像用户在真实页面上一样。
const KEY_DOWN = 40
// Select an item from a React Select dropdown given a label and
// choice label you wish to pick.
export async function selectItem(
container: HTMLElement,
label: string,
choice: string
): Promise<void> {
// Focus and enable the dropdown of options.
fireEvent.focus(getByLabelText(container, label))
fireEvent.keyDown(getByLabelText(container, label), {
keyCode: KEY_DOWN,
})
// Wait for the dropdown of options to be drawn.
await findByText(container, choice)
// Select the item we care about.
fireEvent.click(getByText(container, choice))
// Wait for your choice to be set as the input value.
await findByDisplayValue(container, choice)
}
Run Code Online (Sandbox Code Playgroud)
可以这样使用:
it('selects an item', async () => {
const { container } = render(<MyComponent/>)
await selectItem(container, 'My label', 'value')
})
Run Code Online (Sandbox Code Playgroud)
您可以尝试以下操作来使其正常工作:
您可以添加值为“react-select”的 className 和 classNamePrefix 属性,以便专门选择您要测试的组件。
PS:如果您仍然陷入困境,我鼓励您看一下借用上述答案的对话 - https://spectrum.chat/react-testing-library/general/testing-react-select~ 5857bb70-b3b9-41a7-9991-83f782377581
| 归档时间: |
|
| 查看次数: |
3066 次 |
| 最近记录: |