reactjs - 使用与 typescript react 的 Jest 测试复制到剪贴板方法

标签 reactjs typescript testing jestjs enzyme

我试图确保在用户单击按钮时将正确的值复制到用户剪贴板。这是我的复制方法。我在输入上使用 ref 来访问正确的值。

  protected copyToClipboard() {
   console.log("clicked!");
   const text = this.controls.copyData;

   if (!_.isNil(text)) {
     text.current.focus();
     text.current.select();

     document.execCommand("copy");
     this.setState({copied: true});
   }
 }

对于我的测试:
  test("Ensure right value is copied to clipboard", () => {
    const wrapper = mount(<MyComponent />);

    const copyButton = wrapper.find(".copyBtn");
    copyButton.simulate("click");

    const copyToClipboardSpy = jest.spyOn(document as any, "execCommand");
    wrapper.update();

    expect(copyToClipboardSpy).toHaveBeenCalledWith("copy");
  });

我运行测试时收到的错误是 TypeError: document.execCommand is not a function这是有道理的,但我不确定如何解决这个问题。

我对测试比较陌生,只是想把它放在那里。我还读到我可能无法访问 document.execCommand 但一直在努力寻找一个好的替代方法来劫持测试并访问正在复制的值。我很感激可以就此事提出的任何建议!

最佳答案

发布此信息以防其他人在类似的船上。它不一定要检查值(value),但我管理的一件是用 document.execCommand方法。

我在包装器上方设置了一个模拟函数:

document.execCommand = jest.fn();

有了这个,测试停止抛出 TypeError .然后我的期望包括检查 spy 是否已被调用,期望我的复制状态已更改为 true,以及:
expect(document.execCommand).toHaveBeenCalledWith("copy");

测试通过!该值的一个可能解决方案是查看我是否可以“粘贴”该值然后检查它。如果/何时我可以管理此回复,我将编辑此回复

关于reactjs - 使用与 typescript react 的 Jest 测试复制到剪贴板方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61807378/

相关文章:

javascript - 从 php 调用数组

java - 如何使用 Espresso 测试抽象类?

javascript - 我如何将我的js代码迁移到reactjs并调用它?

reactjs - jsx-a11y 当有 htmlFor 时返回 Form 标签必须有关联的控件

动态分配的 Typescript 2.9 错误

java - 如何测试一个java软件?

testing - NestJS 如何在单元测试中创建新的 Mongoose 模型?

javascript - React SSR 闪烁页面

css - 为什么 &lt;header&gt; 之后的 div 没有显示在标题下方?

ajax - Typescript 语法 - 如何监视 Ajax 请求?