document.addEventListener не является покрытием в JEST - PullRequest
0 голосов
/ 27 января 2020

Я использую JEST для тестирования моего скрипта. В моем статусе покрытия, для instance.init() не распространяется.

  const instance = new RecommendCards();
  document.addEventListener('DOMContentLoaded', () => {
    instance.init();
  });

Как я могу покрыть instance.init()?

1 Ответ

0 голосов
/ 27 января 2020

Вот решение для модульного тестирования:

index.ts:

import { RecommendCards } from './recommendCards';

export function main() {
  const instance = new RecommendCards();
  document.addEventListener('DOMContentLoaded', () => {
    instance.init();
  });
}

recommendCards.ts:

export class RecommendCards {
  public init() {
    return 'real implementation';
  }
}

index.test.ts:

import { main } from './';
import { RecommendCards } from './recommendCards';

jest.mock('./recommendCards', () => {
  const mRecommendCards = { init: jest.fn() };
  return { RecommendCards: jest.fn(() => mRecommendCards) };
});

describe('59927917', () => {
  it('should pass', () => {
    const mockInstance = new RecommendCards();
    document.addEventListener = jest.fn().mockImplementationOnce((event, callback) => {
      callback();
    });
    main();
    expect(document.addEventListener).toBeCalledWith('DOMContentLoaded', expect.any(Function));
    expect(mockInstance.init).toBeCalledTimes(1);
  });
});

Результаты модульных испытаний с отчетом о покрытии:

 PASS  src/stackoverflow/59927917/index.test.ts
  59927917
    ✓ should pass (6ms)

----------|----------|----------|----------|----------|-------------------|
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:        5.92s, estimated 12s

enter image description here

Исходный код: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59927917

...