我试图确保在用户单击按钮时将正确的值复制到用户剪贴板。这是我的复制方法。我在输入上使用 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/