英文:
How to update the value of a `<input type="time" />` using `@testing-library/user-event`?
问题
我需要测试一个用户使用@testing-library/user-event
在React组件中更新具有类型time
和先前defaultValue
的输入值。为什么以下测试失败?如何测试这种用例?
import userEvent from '@testing-library/user-event';
import { render, screen } from '@testing-library/react';
it('should update a value of a time input', async () => {
const user = userEvent.setup();
render(
<label>
Time:
<input type="time" defaultValue="10:30" />
</label>
);
const input = screen.getByLabelText('Time:');
await user.type(input, '06:45');
expect(input).toHaveValue('06:45');
});
这个测试失败,并且出现以下输出。
expect(element).toHaveValue(06:45)
预期元素的值为:
06:45
收到的值为:
10:59
23 | const input = screen.getByLabelText('Time:');
24 | await userEvent.type(input, '06:45');
> 25 | expect(input).toHaveValue('06:45');
| ^
26 | });
如何更新我的测试使其成功?
英文:
I need to test a user that updates the value of a input with type time
and a previous defaultValue
using @testing-library/user-event
in a React component. Why does the following test fail? How can I test this use case?
import userEvent from '@testing-library/user-event';
import { render, screen } from '@testing-library/react';
it('should update a value of a time input', async () => {
const user = userEvent.setup();
render(
<label>
Time:
<input type="time" defaultValue="10:30" />
</label>
);
const input = screen.getByLabelText('Time:');
await user.type(input, '06:45');
expect(input).toHaveValue('06:45');
});
This test fails with the following output.
expect(element).toHaveValue(06:45)
Expected the element to have value:
06:45
Received:
10:59
23 | const input = screen.getByLabelText('Time:');
24 | await userEvent.type(input, '06:45');
> 25 | expect(input).toHaveValue('06:45');
| ^
26 | });
How can I update my test to make it succeed?
答案1
得分: 2
你可以使用initialSelectionStart
和initialSelectionEnd
属性。
这些属性将通过高亮显示当前的所有文本然后用新值替换来清除您的输入。这将改变输入的初始值为新值。
await user.type(input, "06:45", {
initialSelectionStart: 0,
initialSelectionEnd: input.value.length,
});
英文:
You can use initialSelectionStart
and initialSelectionEnd
properties.
These properties will clear your input by highlighting all the current text and then replacing it with the new value. This will change the initial value of the input with the new one.
await user.type(input, "06:45", {
initialSelectionStart: 0,
initialSelectionEnd: input.value.length,
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论