Reactjs 使用react with typescript对复制到剪贴板方法进行Jest测试

Reactjs 使用react with typescript对复制到剪贴板方法进行Jest测试,reactjs,typescript,testing,jestjs,enzyme,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.ex

我试图确保在用户单击按钮时将正确的值复制到剪贴板。这是我的复制方法。我在输入上使用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");
  });
test(“确保将正确的值复制到剪贴板”,()=>{
const wrapper=mount();
const copyButton=wrapper.find(“.copyBtn”);
复制按钮。模拟(“单击”);
const copyToClipboardSpy=jest.spyOn(以任何形式记录,“execCommand”);
wrapper.update();
期望(copyToClipboardSpy)。与(“副本”)一起收集;
});
运行测试时收到的错误是
TypeError:document.execCommand不是一个有意义的函数
,但我不确定如何处理此问题


我对测试还比较陌生,只是想说出来。我还读到,我可能无法访问document.execCommand,但我一直在努力寻找一个好的替代方法来劫持测试并访问正在复制的值。我非常感谢你对此事的任何建议

如果其他人也在类似的船上,请发布此消息。它还不一定检查值,但我管理的一部分是使用
document.execCommand
方法

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

document.execCommand = jest.fn();
这样,测试就停止抛出
TypeError
。然后,我的期望包括检查间谍是否已被调用,期望我的复制状态已更改为true,以及:

expect(document.execCommand).toHaveBeenCalledWith("copy");
考试通过了!该值的一个可能解决方案是查看是否可以“粘贴”该值,然后检查它。如果/当我能够管理此响应时,将编辑此响应