javascript下载功能的单元测试

我需要为以下功能编写单元测试。目前只是检查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);

}


大话西游666
浏览 192回答 1
1回答

杨魅力

这是我的解决方案: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 totalTests:       1 passed, 1 totalSnapshots:   0 totalTime:        4.571s, estimated 8s源代码:https : //github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58445250
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript