javascript下载函数的单元测试

javascript下载函数的单元测试,javascript,unit-testing,download,jestjs,Javascript,Unit Testing,Download,Jestjs,我需要为下面的函数编写一个单元测试。目前正在检查调用了多少次appendChild/removeChild,但我认为这不是最好的测试方法。除此之外,我不知道单元测试应该是什么样子,因为我是测试新手。谢谢你在这方面的帮助 导出默认函数下载(blobUrl,文件名){ const link=document.createElement('a'); link.setAttribute('href',blobUrl); link.setAttribute('download',`${fileName}.

我需要为下面的函数编写一个单元测试。目前正在检查调用了多少次
appendChild/removeChild
,但我认为这不是最好的测试方法。除此之外,我不知道单元测试应该是什么样子,因为我是测试新手。谢谢你在这方面的帮助

导出默认函数下载(blobUrl,文件名){
const link=document.createElement('a');
link.setAttribute('href',blobUrl);
link.setAttribute('download',`${fileName}.pdf`);
link.style.display='none';
document.body.appendChild(链接);
link.click();
document.body.removeChild(link);
}
以下是我的解决方案:

index.ts

导出默认函数下载(blobUrl,文件名){
const link=document.createElement('a');
link.setAttribute('href',blobUrl);
link.setAttribute('download',`${fileName}.pdf`);
link.style.display='none';
document.body.appendChild(链接);
link.click();
document.body.removeChild(link);
}
索引规范ts

从“/”导入下载;
描述('下载',()=>{
测试('应正确下载',()=>{
const mLink={href:'',单击:jest.fn(),下载:'',样式:{display:'},setAttribute:jest.fn()},如有;
const createElementSpy=jest.spyOn(文档'createElement').mockReturnValueOnce(mLink);
document.body.appendChild=jest.fn();
document.body.removeChild=jest.fn();
下载('blobUrl','go');
expect(createElementSpy).toBeCalledWith('a');
expect(mLink.setAttribute.mock.calls.length).toBe(2);
expect(mLink.setAttribute.mock.calls[0]).toEqual(['href','blobUrl']);
expect(mLink.setAttribute.mock.calls[1]).toEqual(['download','go.pdf']);
expect(mLink.style.display).toBe('none');
expect(document.body.appendChild).toBeCalledWith(mLink);
expect(mLink.click).toBeCalled();
期望(document.body.removeChild).toBeCalledWith(mLink);
});
});
100%覆盖率的单元测试结果:

PASS src/stackoverflow/58445250/index.spec.ts
下载
✓ 应正确下载(8ms)
----------|----------|----------|----------|----------|-------------------|
文件|%Stmts |%Branch |%Funcs |%Line |未覆盖行|s|
----------|----------|----------|----------|----------|-------------------|
所有文件| 100 | 100 | 100 | 100 ||
index.ts | 100 | 100 | 100 | 100 ||
----------|----------|----------|----------|----------|-------------------|
测试套件:1个通过,共1个
测试:1项通过,共1项
快照:共0个
时间:4.571s,估计8s

源代码:

不过,要为此编写黑盒测试有点困难,因为可能有不同的技术触发下载。因此,如果您模拟了
文档
对象,那么您可以检查是否添加了指向给定文件的链接,甚至是否单击了该链接。@VLAZ如果该链接被删除(下载函数结束),我如何实际检查该链接?如果您模拟了
文档
,您应该能够禁用删除(只需检查是否调用了该节点)或者即使删除了该节点,也要保持添加该节点。请记住,模拟的
文档
也可以返回模拟的
节点。