javascript下载功能的单元测试

mcm*_*mxc 0 javascript unit-testing download jestjs

我需要为以下功能编写单元测试。目前只是检查被调用的次数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);
}
Run Code Online (Sandbox Code Playgroud)

sli*_*wp2 5

这是我的解决方案:

\n\n

index.ts:

\n\n
export default function download(blobUrl, fileName) {\n  const link = document.createElement(\'a\');\n  link.setAttribute(\'href\', blobUrl);\n  link.setAttribute(\'download\', `${fileName}.pdf`);\n  link.style.display = \'none\';\n\n  document.body.appendChild(link);\n\n  link.click();\n\n  document.body.removeChild(link);\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

index.spec.ts:

\n\n
import download from \'./\';\n\ndescribe(\'download\', () => {\n  test(\'should download correctly\', () => {\n    const mLink = { href: \'\', click: jest.fn(), download: \'\', style: { display: \'\' }, setAttribute: jest.fn() } as any;\n    const createElementSpy = jest.spyOn(document, \'createElement\').mockReturnValueOnce(mLink);\n    document.body.appendChild = jest.fn();\n    document.body.removeChild = jest.fn();\n    download(\'blobUrl\', \'go\');\n    expect(createElementSpy).toBeCalledWith(\'a\');\n    expect(mLink.setAttribute.mock.calls.length).toBe(2);\n    expect(mLink.setAttribute.mock.calls[0]).toEqual([\'href\', \'blobUrl\']);\n    expect(mLink.setAttribute.mock.calls[1]).toEqual([\'download\', \'go.pdf\']);\n    expect(mLink.style.display).toBe(\'none\');\n    expect(document.body.appendChild).toBeCalledWith(mLink);\n    expect(mLink.click).toBeCalled();\n    expect(document.body.removeChild).toBeCalledWith(mLink);\n  });\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n
 PASS  src/stackoverflow/58445250/index.spec.ts\n  download\n    \xe2\x9c\x93 should download correctly (8ms)\n\n----------|----------|----------|----------|----------|-------------------|\nFile      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |\n----------|----------|----------|----------|----------|-------------------|\nAll files |      100 |      100 |      100 |      100 |                   |\n index.ts |      100 |      100 |      100 |      100 |                   |\n----------|----------|----------|----------|----------|-------------------|\nTest Suites: 1 passed, 1 total\nTests:       1 passed, 1 total\nSnapshots:   0 total\nTime:        4.571s, estimated 8s\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n