如何在Jest React测试中触发上/下数字输入旋钮

huangapple go评论57阅读模式
英文:

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(&quot;renders and updates NumberInput&quot;, () =&gt; {
   let value = &quot;5&quot;;
   const setValue = (e) =&gt; value = e.value;

   render(&lt;NumberInput
     label=&quot;Quantity&quot;
     name=&quot;quantity&quot;
     value={value}
     onChange={setValue}
     step={0.5}
     min={0.05}
   /&gt;);

   let element = screen.getByRole(&#39;spinbutton&#39;);
   expect(element).toBeInTheDocument();

   fireEvent.change(element, { target: { value: &quot;10&quot; }});

   expect(value).toEqual(&quot;10&quot;);
});

How could I test triggering the up/down spin buttons?

答案1

得分: 0

虽然我无法弄清楚如何模拟点击按钮,但我确实找到了如何测试stepmin属性与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(() =&gt; {
   expect(element).toHaveFocus();

   userEvent.keyboard(&#39;[ArrowDown]&#39;).then(() =&gt; {
      expect(value).toEqual(&quot;9.5&quot;);
   });
});

huangapple
  • 本文由 发表于 2023年2月13日 23:44:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75438135.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定