【问题标题】:How to paste clipboard data using React Testing Library?如何使用 React 测试库粘贴剪贴板数据?
【发布时间】:2021-02-10 20:43:29
【问题描述】:

我正在尝试将剪贴板中已有的文本粘贴到文本框中,但我不明白如何使用“eventInit”来执行此操作。我已阅读有关如何将文本粘贴到文本框中的文档,但不清楚如何使用 eventInit。

如何使用 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...
});

Documentation:

【问题讨论】:

  • 您能提供您的copy to clipboard 代码吗?
  • 无需设置输入即可粘贴内容;只需在您正在测试的按钮内模拟您正在调用的函数,并使用 id 值检查它是否被调用,类似于这个问题stackoverflow.com/questions/61807378/…
  • 你不需要粘贴你的剪贴板,你可以假设模拟文本作为你的剪贴板文本。 userEvent.paste(getByRole('textbox', { name: /paste your greeting/i }), text) 表示将剪贴板文本模拟到目标文本框中。在此粘贴操作之后,您只需检查目标文本框的内容是否包含模拟文本。

标签: reactjs unit-testing testing integration-testing react-testing-library


【解决方案1】:

userEvent.paste 不会帮助您:它适用于测试用户将某些文本粘贴到输入中时会发生什么情况的情况。 React 测试库实际上并没有一个剪贴板来保存被复制的值。

我会做什么:

  • 模拟“复制到剪贴板”功能,因此您的测试只检查用户单击按钮时是否调用了正确的功能
  • 为复制到剪贴板功能编写单独的单元测试(如果有意义,您必须模拟很多浏览器 api,这样手动测试才有意义)

如果你真的想测试复制到剪贴板的工作,你需要编写一个运行实际浏览器的端到端测试。至少 Cypress 提供了读取剪贴板内容的 API。

【讨论】:

    【解决方案2】:

    另一种选择是做类似的事情

    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

    【讨论】:

    • 很棒的文章!尽管我强烈建议切换到基于函数的组件而不是基于旧类的组件,尤其是现在我们可以访问挂钩。它不那么冗长,更简单,并且是一种更现代/更常见的处理方法。有几篇关于如何/为什么要的文章(这是随机的一篇 - dev.to/danielleye/…
    猜你喜欢
    • 2017-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-06
    相关资源
    最近更新 更多