【问题标题】:Jest test for a copy to clipboard method using react with typescript使用与 typescript 反应的复制到剪贴板方法的 Jest 测试
【发布时间】:2020-08-31 13:53:56
【问题描述】:

我试图确保在用户单击按钮时将正确的值复制到剪贴板。这是我的复制方法。我在输入上使用 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,但一直在努力寻找一个好的替代方案来劫持测试并访问被复制的值。我很感激可以就此事提供的任何建议!

【问题讨论】:

    标签: reactjs typescript testing jestjs enzyme


    【解决方案1】:

    发布此内容以防其他人遇到类似情况。它还不一定会检查值,但我管理的一项是使用 document.execCommand 方法。

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

    document.execCommand = jest.fn();
    

    这样,测试停止抛出TypeError。然后我的期望包括检查间谍是否已被调用,期望我的副本状态已更改为 true,并且:

    expect(document.execCommand).toHaveBeenCalledWith("copy");
    

    测试通过!该值的一个可能解决方案是查看我是否可以“粘贴”该值然后检查它。如果/当我能做到这一点时,我会编辑这个回复

    【讨论】:

    • 你有没有想过如何检查复制的值?
    • 任何人都曾经得到工作对剪贴板副本和/或粘贴的价值进行断言?
    • @suzu94,如何查看复制的值?
    • 好吧,既然你在模拟 ecexCommand("copy") 调用,文本并没有真正被复制。这只是测试调用了 execCommand。
    猜你喜欢
    • 2021-03-06
    • 2020-12-19
    • 1970-01-01
    • 2019-06-13
    • 1970-01-01
    • 2021-07-07
    • 2019-07-18
    • 2016-07-19
    • 2010-11-17
    相关资源
    最近更新 更多