我在Angular 6中拥有此类服务:
export class AppService {
setValues(): Observable<any> {
const vm: any = this;
return new Observable(observer => {
vm.currentValues().subscribe(data => {
// continue modifying data and reset it
});
});
}
public currentValues(): Observable<any> {
return new Observable(observer => {
observer.next('data goes here')
});
}
}
currentValues()是相当随机的,因此无法对其进行中继。如何在我的unittest文件中模拟它并在测试setValues()方法时使用它?
我尝试了以下方法,但看不到如何使用?
export function mockCurrentValues () : Observable<any> {
return of(
'data'
)
}
答案 0 :(得分:1)
假设AppService
是@Injectable()
,并且您正在为提供程序编写单元测试。您可以使用spys
提供的Jasmine Framework
https://jasmine.github.io/2.0/introduction.html#section-Spies
import { getTestBed, TestBed } from '@angular/core/testing';
import { AppService } from 'path/to/app/service';
import { of } from 'rxjs';
describe( 'App Service', function() {
let appService : AppService;
beforeEach( function() {
TestBed.configureTestingModule( {
providers: [ AppService ],
} );
const injector = getTestBed();
appService = injector.get( AppService );
spyOn( appService, 'currentValues' ).and.callFake( () => {
return of( 'data' );
} );
} );
describe( 'setValues', function() {
it( 'should set correct values', function() {
appService.setValues().subscribe();
// setValues will receive 'data' from the spy we just created while calling currentValues() method
// write your unit tests here
} );
} );
} );
答案 1 :(得分:0)
您可以发布完整的代码吗?无论如何,我认为您应该这样尝试returnValue:
const injector = getTestBed();
appService = injector.get( AppService );
// spy the internal method setValues() calls now and return observable
spyOn( appService, 'currentValues' ).and.returnValue(of(data));
appService.setValues().subscribe(data=>{
// do your test here
done()
}
)