如何使用 React 测试库粘贴剪贴板数据? [英] How to paste clipboard data using React Testing Library?
问题描述
我正在尝试将剪贴板中已有的文本粘贴到文本框中,但我不明白如何使用eventInit"去做这个.我已阅读有关如何将文本粘贴到文本框中的文档,但不清楚如何使用 eventInit.
I'm trying to paste text that's already in my clipboard into a textbox, but I dont understand how to use "eventInit" to do this. I've read the documentation on how to paste text into a textbox, but it isn't clear on how to use eventInit.
如何使用 userEvent 将剪贴板中的文本粘贴到文本框中?
How do i paste text that's in my clipboard into a textbox using userEvent?
这是我的代码:
test('Copy id button copies correct id', async () => {
const { getAllByLabelText, debug, getByText } = render(
<MockedProvider mocks={mocks} addTypename={false}>
<History />
</MockedProvider>
);
const textbox = <input type="text" />;
await waitFor(() => new Promise((resolve) => setTimeout(resolve, 0)));
const button = getAllByLabelText('click to copy id')[0];
fireEvent.click(button);
// userEvent.paste(textbox,_,) unsure what to do here...
});
推荐答案
另一种选择是做类似的事情
Another option would be to do something like
test('Pasting fires onPaste event which returns clipboard data', () => {
const pasted = jest.fn(() => null);
const changed = jest.fn(() => null);
render(
<PasteComponent paste={pasted} changeEvent={changed} data-testid='paste-input' />);
const PhoneNumberElement = screen.queryByTestId('paste-input');
const paste = createEvent.paste(PhoneNumberElement, {
clipboardData: {
getData: () => '123456',
},
});
fireEvent(PhoneNumberElement, paste);
expect(pasted).toHaveBeenCalled();
expect(pasted).toHaveBeenCalledWith('123456');
});
我写了一篇关于它的帖子 - https://medium.davidendersby.me/2-ways-to-trigger-the-onpaste-event-with-testing-library-1502c5fdb9e
I wrote up a post on it - https://medium.davidendersby.me/2-ways-to-trigger-the-onpaste-event-with-testing-library-1502c5fdb9e
这篇关于如何使用 React 测试库粘贴剪贴板数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!