suz*_*u94 3 testing typescript reactjs jestjs enzyme
我试图确保在用户单击按钮时将正确的值复制到用户剪贴板。这是我的复制方法。我在输入上使用 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});
}
}
Run Code Online (Sandbox Code Playgroud)
对于我的测试:
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");
});
Run Code Online (Sandbox Code Playgroud)
我运行测试时收到的错误是 TypeError: document.execCommand is not a function有道理的,但我不确定如何解决这个问题。
我对测试比较陌生,只是想把它放在那里。我还读到我可能无法访问 document.execCommand 但一直在努力寻找一个好的替代方法来劫持测试并访问正在复制的值。我很感激可以就此事提出的任何建议!
suz*_*u94 11
发布此信息以防其他人在类似的船上。它不一定要检查值,但我管理的一件是使用document.execCommand方法。
我在包装器上方设置了一个模拟函数:
document.execCommand = jest.fn();
Run Code Online (Sandbox Code Playgroud)
有了这个,测试停止抛出TypeError. 然后我的期望包括检查 spy 是否已被调用,期望我的复制状态已更改为 true,以及:
expect(document.execCommand).toHaveBeenCalledWith("copy");
Run Code Online (Sandbox Code Playgroud)
测试通过!该值的一个可能解决方案是查看我是否可以“粘贴”该值然后检查它。如果/何时我可以管理此回复,我将编辑此回复
| 归档时间: |
|
| 查看次数: |
5344 次 |
| 最近记录: |