【发布时间】:2020-05-12 22:36:49
【问题描述】:
我是非常新的 Jasmine 单元测试用例。我的场景可能很简单,但我不确定如何为下面的课程涵盖 ngInit 的测试用例。谁能帮帮我,
export class Component1 implements OnInit {
details$: Observable<any>;
name: string;
error: string
constructor(private service1: Service1, private service2: Service2) { }
ngOnInit() {
this.service1.service1Subject.subscribe( info => {
if(info['url']){
this.details$ = this.service2.get(info['url'])
this.details$.subscribe(
(info) => { this.name = info['name']};
(error) => { this.erro = error['error']};
);
}
});
}
}
测试用例:
describe('Component1', () => {
let component: Component1;
let fixture: ComponentFixture<Component1>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [Component1],
imports: [
HttpClientTestingModule, CommonModule
],
providers: [Service1, Service2]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(Component1);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should call Get Data', () => {
const service2: Service2 = TestBed.get(Service2);
const spy = jest.spyOn(service2, 'get').mockImplementation(() => {
return {
info : [...],
name : ''
}
});
component.ngOnInit();
expect(spy).toHaveBeenCalled();
});
});
这里的问题是,我不确定如何模拟 service1,RxJS 主题。请有人帮助我。
【问题讨论】:
-
在您尝试使用 observable 测试您的代码之前,我建议您更深入地了解您可以使用的运算符。嵌套
subscribe是一种巨大的代码气味,您应该使用switchMap、concatMap、mergeMap等
标签: angular jasmine jestjs karma-jasmine angular-test