gpt4 book ai didi

testing-library - 使用测试库选择下拉元素

转载 作者:行者123 更新时间:2023-12-05 02:55:06 25 4
gpt4 key购买 nike

显然我根本不了解测试库。它们具有“单击”功能,但似乎没有从选择元素中选择简单下拉选项的功能。这是失败的,表示选择了 0,而不是预期的 1。如何使选择生效?


import React from "react";
import {render} from '@testing-library/react'
import {screen} from '@testing-library/dom'

let container: any;
beforeEach(() => {
container = document.createElement('div');
document.body.appendChild(container);
});

afterEach(() => {
document.body.removeChild(container);
container.remove();
container = null;
});

it('AddRental should display', () => {
render(<select name="town" data-testid="town" className="form-control"
aria-label="Select the Town">
<option value="0">--Town--</option>
<option value="1">My town</option>
<option value="2">Your Town</option>
<option value="3">The other town</option>
</select>, {container});
const dropdown = screen.getByTestId('town');
expect(dropdown.value)
.toBe('0');
dropdown.click();
const athabascaOption = screen.getByText('My town');
athabascaOption.click();
const byTestId = screen.getByTestId('town');
expect(byTestId.value)
.toBe('1')
});

最佳答案

您可以使用 fireEvent以此目的。它可以从 @testing-library/react 导入(顺便说一下,为方便起见,screen 也可以):

import {render, screen, fireEvent} from '@testing-library/react'

这是为使用此功能而重写的测试用例:

render(
<select
name="town"
data-testid="town"
className="form-control"
aria-label="Select the Town"
>
<option value="0">--Town--</option>
<option value="1">My town</option>
<option value="2">Your Town</option>
<option value="3">The other town</option>
</select>,
{ container },
);
const dropdown = screen.getByTestId('town') as HTMLSelectElement;
expect(dropdown.value).to.equal('0');
fireEvent.change(dropdown, { target: { value: '1' } });
expect(dropdown.value).to.equal('1');

为了进一步解释,在 this GitHub issue 中有一些有用的讨论。和 this CodeSandbox from a comment on the issue .

关于testing-library - 使用测试库选择下拉元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61475223/

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