为了账号安全,请及时绑定邮箱和手机立即绑定

javascript下载功能的单元测试

javascript下载功能的单元测试

大话西游666 2021-11-25 15:27:45
我需要为以下功能编写单元测试。目前只是检查appendChild/removeChild被调用了多少次,但我认为这不是测试这个的最好方法。除此之外 - 不知道单元测试应该是什么样子,因为我是测试新手。感谢您对此的任何帮助!export default function download(blobUrl, fileName) {  const link = document.createElement('a');  link.setAttribute('href', blobUrl);  link.setAttribute('download', `${fileName}.pdf`);  link.style.display = 'none';  document.body.appendChild(link);  link.click();  document.body.removeChild(link);}
查看完整描述

1 回答

?
杨魅力

TA贡献1811条经验 获得超6个赞

这是我的解决方案:


index.ts:


export default function download(blobUrl, fileName) {

  const link = document.createElement('a');

  link.setAttribute('href', blobUrl);

  link.setAttribute('download', `${fileName}.pdf`);

  link.style.display = 'none';


  document.body.appendChild(link);


  link.click();


  document.body.removeChild(link);

}

index.spec.ts:


import download from './';


describe('download', () => {

  test('should download correctly', () => {

    const mLink = { href: '', click: jest.fn(), download: '', style: { display: '' }, setAttribute: jest.fn() } as any;

    const createElementSpy = jest.spyOn(document, 'createElement').mockReturnValueOnce(mLink);

    document.body.appendChild = jest.fn();

    document.body.removeChild = jest.fn();

    download('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();

    expect(document.body.removeChild).toBeCalledWith(mLink);

  });

});

100% 覆盖率的单元测试结果:


 PASS  src/stackoverflow/58445250/index.spec.ts

  download

    ✓ should download correctly (8ms)


----------|----------|----------|----------|----------|-------------------|

File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |

----------|----------|----------|----------|----------|-------------------|

All files |      100 |      100 |      100 |      100 |                   |

 index.ts |      100 |      100 |      100 |      100 |                   |

----------|----------|----------|----------|----------|-------------------|

Test Suites: 1 passed, 1 total

Tests:       1 passed, 1 total

Snapshots:   0 total

Time:        4.571s, estimated 8s

源代码:https : //github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58445250


查看完整回答
反对 回复 2021-11-25
  • 1 回答
  • 0 关注
  • 191 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信