簡體   English   中英

如何在 Angular 9 組件單元測試中調用假函數

[英]How to call a fake function in Angular 9 component unit test

我有一個包含兩種方法的角度組件

class MyComponent {

    constructor() {
     ...
    }

    loadDataSource() {
     ...
    }
    
    runFilter() {
      //some other logic here
      this.loadDataSource();
    }
}

我有一個單元測試

describe('running filters', () => {
      beforeEach(() => {
        component.runFilter();
        const spy = jasmine.createSpyObj(['loadDataSource']);
        spy.loadDataSource.and.callFake(function() { });
      });
     
      it('should call load data source', () => {
        expect(component.loadDataSource).toHaveBeenCalled();
      });
 });

但是,這似乎仍然在調用 runFilter 時調用了 loadDataSource 的實際實現,而不是我提供的空假函數。

我如何測試調用 runFilter 時調用的 loadDataSource 方法,而不實際調用實際實現? 這樣做的原因是我不希望調用 loadDataSource 的任何邏輯。

嘗試這個

 describe('running filters', () => {
          beforeEach(() => {
            spyOn(component, 'loadDataSource').and.callFake();
          });
         
          it('should call load data source', () => {
            component.runFilter();
            expect(component.loadDataSource).toHaveBeenCalled();
          });
     });

暫無
暫無

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

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