使用typecript的react复制到剪贴板方法的Jest测试。

问题描述 投票:0回答:1

我试图确保当用户点击按钮时,正确的值被复制到用户剪贴板。这是我的复制方法。我使用输入的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个回答
0
投票

发这个帖子是为了防止有人遇到类似的情况。它的还不一定能检查到值,但有一块我管理的是与 document.execCommand 方法。

我在包装器上面设置了一个模拟函数。

document.execCommand = jest.fn();

这样一来,测试就不再抛出 TypeError. 然后我的期望值包括检查间谍是否被调用,期望我的副本状态已经改变为true,然后。

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

测试通过!一个可能的解决方法是看看我是否可以 "粘贴 "该值,然后检查它。如果我可以做到这一点,将编辑此回复。

© www.soinside.com 2019 - 2024. All rights reserved.