Angular 测试rxjs操作符内部的代码
我对angular jasmine测试是新手,我想开始在我的应用程序上使用它,但我在测试覆盖范围中包含rxjs操作符时遇到了问题Angular 测试rxjs操作符内部的代码,angular,karma-jasmine,Angular,Karma Jasmine,我对angular jasmine测试是新手,我想开始在我的应用程序上使用它,但我在测试覆盖范围中包含rxjs操作符时遇到了问题 saveChanges(){ this.isSaveSuccessful = false; this.saveService.httpGetCall() .pipe(tap( ret =>{ line 1; line 2; }), map( ret => { line 3
saveChanges(){
this.isSaveSuccessful = false;
this.saveService.httpGetCall()
.pipe(tap( ret =>{
line 1;
line 2;
}),
map( ret => {
line 3;
line 4;
}),
finalize(()=>{
if(someBoolean) this.isSaveSuccessful = true;
})).subscribe()
}
测试中不包括第1、2、3、4行
it('should save',()=>{
component.saveChanges();
expect(component.isSaveSuccessful).toBeTrue();
})
您需要模拟this.saveService.httpGetCall()返回的内容, 这里有一个关于如何做到这一点的完整详细的解释。 然后,一旦被嘲笑,你就可以这样做
it('should save',()=>{
component.saveChanges();
mockedHttp.subscribe(result => {
expect(result).toBe("your desired result");
})
expect(component.isSaveSuccessful).toBeTrue();
})
在Jasmine中模拟
saveService
,并通过依赖项注入(DI)为您的组件/服务提供它:
我认为您需要两件事:1)使用不同的值模拟来自httpGetCall
的响应,以增加覆盖率2)fixture.detectChanges()
以响应所做的更改
describe('MyComponent', () => {
let saveService: SaveService:
const yourCustomHttpGetCallResult = ...;
beforeEach(() => {
const saveServiceMock = jasmine.createSpyObj('SaveService', {
httpGetCall: of(yourCustomHttpGetCallResult),
});
TestBed.configureTestingModule({
declarations: [
MyComponent,
],
providers: [
{ provide: SaveService, useValue: saveServiceMock },
],
});
// create a component fixture
...
saveService = TestBed.inject(SaveService);
});
it('should cover the lines 1, 2, 3, 4', () => {
component.saveChanges();
});
it('should call saveChanges with another result', () => {
const newCustomValue = ...;
saveService.httpGetCall.and.returnValue(of(newCustomValue));
component.saveChanges();
});
});