简体   繁体   中英

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

I have an angular component containing two methods

class MyComponent {

    constructor() {
     ...
    }

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

And I have a unit test

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();
      });
 });

However, this seems to still call the actual implementation of loadDataSource when runFilter is called, instead of the empty fake function I provided.

How may I test that loadDataSource method was called when I call runFilter, without actually invoking the actual implementation? The reason for doing so is I do not want any of the logic for loadDataSource invoked.

Try this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM