用打字稿反应对复制到剪贴板的方法进行开玩笑的测试 [英] Jest test for a copy to clipboard method using react with typescript
问题描述
我试图确保在用户单击按钮时将正确的值复制到用户剪贴板.这是我的复制方法.我在输入上使用了ref来访问正确的值.
I am trying to ensure that the right value is copied to the users clipboard when they click a button. This is my copy method. I am using a ref on the input to access the right value.
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不是一个函数
,这很有意义,但是我不确定如何实现.
The error I receive when I run the test is TypeError: document.execCommand is not a function
which makes sense, but I am unsure how to approach this.
对于测试,我还是比较陌生,只是将其放在那里.我还读到我可能无法访问document.execCommand,但一直在努力寻找一种劫持测试并访问要复制的值的好方法.我很高兴就此事提供任何建议!
I am relatively new to testing, just to put that out there. I also have read that I may not be able to access the document.execCommand but have struggled to find a good alternative to hijack the test and access the value being copied. I appreciate any advice that can be given on the matter!
推荐答案
如果其他人都在类似的船上,请将其发布.它并不一定要检查该值,但是我管理的一个部分是使用 document.execCommand
方法.
Posting this in case anyone else was in a similar boat. It's doesn't necessarily check the value yet, but one piece I managed was with the document.execCommand
method.
我在包装器上方设置了一个模拟函数:
I set up a mock function above the wrapper:
document.execCommand = jest.fn();
有了这个,测试就停止抛出 TypeError
.然后我的期望包括检查间谍是否已被呼叫,期望我的复制状态已更改为true,以及:
With this, the test stopped throwing the TypeError
. Then my expectations included checking for the spy to have been called, expect my copy state to have changed to true, and:
expect(document.execCommand).toHaveBeenCalledWith("copy");
测试通过!该值的一种可能的解决方案是查看是否可以粘贴"该值,然后进行检查.当/我可以管理该回复时,将对其进行编辑
Test passes! A possible solution for the value is to see if I can "paste" the value and then check it. Will edit this response if/when I can manage that
这篇关于用打字稿反应对复制到剪贴板的方法进行开玩笑的测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!