问题描述
我具有此功能,可以将当前网址复制到剪贴板。
const copyToClipboard = (str) => {
const tmpElm = document.createElement('textarea');
tmpElm.value = window.location.href;
tmpElm.setAttribute('readonly','');
tmpElm.style.position = 'absolute';
tmpElm.style.left = '-9999px';
document.body.appendChild(tmpElm);
tmpElm.select();
document.execCommand('copy');
document.body.removeChild(tmpElm);
};
我究竟该如何测试此功能? (使用未嵌套在浏览器中的测试框架(如jest)。
解决方法
我认为您能做的最简单的测试是对execComand
fn进行存根
document.execCommand = jest.fn();
然后您可以编写类似的测试
expect(document.execCommand).toHaveBeenCalledWith("copy");