首页 > 解决方案 > 如何在 void 函数中测试对函数范围变量的分配?

问题描述

我有一个函数,由于代码覆盖率,我需要对其进行测试。

const downloadPdfDataContent = (title: string, url: string): void => {
  const link = document.createElement('a');
  link.target = title;
  link.href = url;
  link.download = title;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
};

如何完成对变量和文档对象的分配测试?我想我需要使用 spyOn .. 但我不知道具体如何,因为变量只存在于函数范围内。我想过简单地返回变量,但如果可能的话,我想阻止这种情况。

标签: angulartypescriptunit-testingjestjsjasmine

解决方案


您可以使用jest.spyOn()来模拟每个 DOM 操作。

例如

index.ts

export const downloadPdfDataContent = (title: string, url: string): void => {
  const link = document.createElement('a');
  link.target = title;
  link.href = url;
  link.download = title;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
};

index.test.ts

import { downloadPdfDataContent } from '.';

describe('67634069', () => {
  afterEach(() => {
    jest.restoreAllMocks();
  });
  it('should pass', () => {
    const mAnchor = ({
      target: '',
      href: '',
      download: '',
      click: jest.fn(),
    } as unknown) as HTMLAnchorElement;
    const createElementSpy = jest.spyOn(document, 'createElement').mockReturnValueOnce(mAnchor);
    const appendChildSpy = jest.spyOn(document.body, 'appendChild').mockImplementation();
    const removeChildSpy = jest.spyOn(document.body, 'removeChild').mockImplementation();
    URL.revokeObjectURL = jest.fn();
    downloadPdfDataContent('teresa teng', 'example.com');
    expect(createElementSpy).toBeCalledWith('a');
    expect(appendChildSpy).toBeCalledWith(
      expect.objectContaining({
        target: 'teresa teng',
        href: 'example.com',
        download: 'teresa teng',
      })
    );
    expect(mAnchor.click).toBeCalledTimes(1);
    expect(removeChildSpy).toBeCalledWith(
      expect.objectContaining({
        target: 'teresa teng',
        href: 'example.com',
        download: 'teresa teng',
      })
    );
    expect(URL.revokeObjectURL).toBeCalledWith('example.com');
  });
});

测试结果:

 PASS  examples/67634069/index.test.ts (8.691 s)
  67634069
    ✓ should pass (4 ms)

----------|---------|----------|---------|---------|-------------------
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:        9.612 s

推荐阅读