【发布时间】: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