簡體   English   中英

document.addEventListener 不在 JEST 的覆蓋范圍內

[英]document.addEventListener is not coverage in JEST

我正在使用 JEST 來測試我的腳本。 在我的覆蓋狀態中, instance.init()沒有被覆蓋。

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

我如何覆蓋instance.init()

這是單元測試解決方案:

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

在此處輸入圖片說明

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM