英文:
How to trigger up/down number input spin buttons in Jest React testing
问题
I'm attempting to test using @testing-library/react
& @testing-library/jest-dom
a number input component and I haven't figured out how to test triggering the up/down spin buttons of the input.
test("renders and updates NumberInput", () => {
let value = "5";
const setValue = (e) => value = e.value;
render(<NumberInput
label="Quantity"
name="quantity"
value={value}
onChange={setValue}
step={0.5}
min={0.05}
/>);
let element = screen.getByRole('spinbutton');
expect(element).toBeInTheDocument();
fireEvent.change(element, { target: { value: "10" }});
expect(value).toEqual("10");
});
How could I test triggering the up/down spin buttons?
英文:
I'm attempting to test using @testing-library/react
& @testing-library/jest-dom
a number input component and I haven't figured out how to test triggering the up/down spin buttons of the input.
test("renders and updates NumberInput", () => {
let value = "5";
const setValue = (e) => value = e.value;
render(<NumberInput
label="Quantity"
name="quantity"
value={value}
onChange={setValue}
step={0.5}
min={0.05}
/>);
let element = screen.getByRole('spinbutton');
expect(element).toBeInTheDocument();
fireEvent.change(element, { target: { value: "10" }});
expect(value).toEqual("10");
});
How could I test triggering the up/down spin buttons?
答案1
得分: 0
虽然我无法弄清楚如何模拟点击按钮,但我确实找到了如何测试step
和min
属性与userEvent.keyboard
一起使用的方法。这将触发输入的上/下事件,与在我的情况下点击上/下旋转按钮相同。
userEvent.click(element).then(() => {
expect(element).toHaveFocus();
userEvent.keyboard('[ArrowDown]').then(() => {
expect(value).toEqual("9.5");
});
});
英文:
While I couldn't figure out how to simulate clicking the buttons, I did figure out how to test the step
and min
props working with the userEvent.keyboard
. This triggers the up/down events of an input which in my case is the same as clicking the up/down spin buttons.
userEvent.click(element).then(() => {
expect(element).toHaveFocus();
userEvent.keyboard('[ArrowDown]').then(() => {
expect(value).toEqual("9.5");
});
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论