gpt4 book ai didi

javascript - 在 React 测试库中发现多个元素错误

转载 作者:行者123 更新时间:2023-12-05 00:25:18 27 4
gpt4 key购买 nike

我在查询时遇到问题,我正在尝试获取两个 radio 输入,其中一个没有任何问题,但另一个 React 测试库抛出错误:It Found multiple elements with the role "radio" and name /to/i:查询

test('Render form with default items', () => {
const handleUpdateValue = jest.fn();
const handleNextStep = jest.fn();
render(
<Form
handleNextStep={handleNextStep}
updateValue={handleUpdateValue}
transferFundsValues={{}}
/>
);

const amountInput = screen.getByLabelText(/amount/i);
const fromRadio = screen.getByLabelText(/from/i);
const toRadio = screen.getByLabelText(/to/i);
const messageInput = screen.getByLabelText(/message/i);

const continueButton = screen.getByRole('button', { name: /continue/i });
const cancelButton = screen.getByRole('button', { name: /cancel/i });

// If no value has been entered to the inputs, the continue button must be
// disabled
expect(continueButton).toBeDisabled();
});
html结构
<label for="transferFunds_from" class="ant-form-item-required" title="From">From</label>
<input id="transferFunds_from" type="radio" class="ant-radio-button-input" value="">

<label for="transferFunds_to" class="ant-form-item-required" title="To">To</label>
<input id="transferFunds_to" type="radio" class="ant-radio-button-input" value="">
RTL 引发的错误
 TestingLibraryElementError: Found multiple elements with the role "radio" and name `/to/i`

Here are the matching elements:

<input
class="ant-radio-button-input"
id="transferFunds_from"
type="radio"
value=""
/>

<input
class="ant-radio-button-input"
id="transferFunds_to"
type="radio"
value=""
/>
我不知道是我在 HTML 结构中做错了什么,还是 React 测试库错误。

最佳答案

只是一个快速提示,如果您有多个匹配元素,您可以这样查询:
HTML:

<a href="/my-element">My element</a>
<a href="/my-element">My element</a>
测试:
test('renders my element', () => {
let link = screen.getAllByText('My element')[0] as HTMLAnchorElement;
expect(link.href).toContain('/my-element');
});

关于javascript - 在 React 测试库中发现多个元素错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68943625/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com