简体   繁体   中英

Jasmine unit test spyOn not working in callback function

I am using ag-grid and I need to write Jasmine unit test on a piece of code. This code calls our rest server using a class we called RestService and I want to use spyOn to mock those calls and responses. In other places in the code I use spyOn(RestService, 'function').and.returnValue() and it works no problem at all. This code is automatically called by ag-grid and it is in a datasource object that has a getRows function in it. In here it calls the api to return the next page of data. The info can be found on https://www.ag-grid.com/javascript-grid-infinite-scrolling/

var dataSource = {
    rowCount: null,
    getRows: function(params) {
        console.log("asking for " + params.startRow + " to " + params.endRow);
        // rest service call happens in here
        // something like params.context.mycontext.restService.fetchNextRows(data);
    }
}

I have a spyOn with spyOn(restService, 'fetchNextRows').and.returnValue(Observable.of(something)) but it won't work for this. It tries to actually call the rest service and fails because that is not running during the unit test. Does anyone know a workaround?

my spec.ts uses:

 TestBed.configureTestingModule(
 imports everything i use + has 
 providers: [RestService]
 ).compileComponents();

 let restService = TestBed.get("RestService");
 spyOn(restService, 'fetchNextRows').and.returnValue(Observable.of("mocked json"));

 fixture = TestBed.createComponent(ActionComponent);
 component = fixture.componentInstance;

在您的spec.ts ,从TestBed请求RestService时不得使用双引号。

let restService = TestBed.get(RestService); 

Although I have found a solution, I still don't know why spyOn won't work in these cases with the getRows function.

Instead of using spyOn, create a spy object and provide it instead of the actual service.

Before TestBed.configureTestingModule(...) in your .spec.ts , add this:

let restServiceStub = jasmine.createSpyObj('RestService', ['fetchNextRows']);
restServiceStub.fetchNextRows.and.returnValue(Observable.of("mocked JSON"));

Now, provide it to your test configuration instead of the actual service:

TestBed.configureTestingModule(
    imports everything i use + has 
    providers: [{
        provide: RestService,
        useValue: restServiceStub
    }]
).compileComponents();

I'm using this for my AgGrid server side tables and it works. Still, I don't understand why the spyOn on the service spyOn(RestService, 'fetchNextRows').and.returnValue(Observable.of("mocked JSON") works for all calls except those made by AgGrid.

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