Модульный тест для функции загрузки JavaScript - PullRequest
0 голосов
/ 18 октября 2019

Мне нужно написать модульный тест для функции ниже. Сейчас просто проверяю, сколько раз был вызван 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 Ответ

1 голос
/ 21 октября 2019

Вот мое решение:

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

...