簡體   English   中英

如何在單元測試中模擬 TS 類

[英]How to mock TS class in unit tests

考慮以下代碼片段:

import {Calendar} from '@fullcalendar/core';

...

ngAfterViewInit() {
  this.calendar = new Calendar(this.element.nativeElement, config);
  this.calendar.render();
}

我正在使用 fullcalendar 插件,但它與我原來的問題無關,我認為,它可能是任何其他依賴項。 所以插件創建了一個日歷視圖。 由 fullcalendar 團隊來測試日歷行為,而我負責測試日歷集成。 所以我需要測試日歷是否已使用正確的配置初始化,因此我想省略真正的構造函數並檢索參數。 而且我不想創建日歷的實例。

如何在我的測試中模擬Calendar類?

包裝您的庫調用是一種很好的做法。 首先,測試它們更容易,如果庫接口會發生變化,您只需在一個位置更改代碼,並在其余代碼中保留您自己的接口。

因此,您的問題的一種解決方案是將日歷創建包裝在工廠服務中,例如:

@Injectable({providedIn:'root'})
export class FullcalendarFactoryService{

  public buildCalendar(element:HTMLElement,config:any){
    return new Calendar(element,config);
  }
}

在你的組件中,你必須注入你的工廠服務並像這樣使用它:

constructor(public calenderFactory:FullcalendarFactoryService) {
}

ngAfterViewInit(): void {
    this.calendar = this.calenderFactory.buildCalendar(this.element.nativeElement,this.config);
    this.calendar.render();
}

為了測試,你可以簡單地模擬你的工廠函數,如下所示:

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        YourComponent
      ],
      providers: [{
        provide: FullcalendarFactoryService,
        useClass: class {
          buildCalendar = jasmine.createSpy('buildCalendar').and.returnValue({
            render: () => true
          });
        }
      }
      ]
    }).compileComponents();

    calendarFactory = TestBed.get(FullcalendarFactoryService);

}));

it('should call factory method with element and config', () => {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();

    expect(calendarFactory.buildCalendar).toHaveBeenCalledWith(fixture.componentInstance.element.nativeElement, fixture.componentInstance.config);
  });

更新:

要測試服務buildCalendar函數是否返回Calendar一個實例,您將測試您的服務,如下所示:

import {FullcalendarFactoryService} from './fullcalendar-factory.service';
import {Calendar} from '@fullcalendar/core';
import dayGridPlugin from '@fullcalendar/daygrid'

describe('calendar factory service', () => {
  let factory:FullcalendarFactoryService;

  beforeEach(() => {
    factory = new FullcalendarFactoryService();
  })

  it('should return calender instance',() => {
    expect(factory.buildCalendar(document.createElement('test'),{plugins:[dayGridPlugin]})).toEqual(jasmine.any(Calendar))
  })
})

暫無
暫無

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

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