【发布时间】:2018-02-16 23:46:45
【问题描述】:
我不熟悉编写单元测试并试图弄清楚为组件中的注入服务编写测试。
组件:
constructor(private _assessmentService: AssessmentDataService){
}
ngOnInit(){
const assessmentSub: Subscription = this._assessmentService.getAssessmentQuestions().subscribe(responseData => {
const obj = responseData.assessment;
assessmentSub.unsubscribe();
});
}
服务:
getAssessmentQuestions(){
return this._http.get('./assets/data/data.json').map(response => response.json());
}
模拟服务:
export const assessmentMockData = {
'assessment': [{
'id': 1,
'question': 'Qeustion 1',
'options': [
{
'id': 1,
'option': 'option 1',
'score': 20
},
{
'id': 2,
'option': 'option 1',
'score': 30
},
{
'id': 3,
'option': 'option 1',
'score': 10
},
{
'id': 4,
'option': 'option 1',
'score': 0
}
],
'selected': 2
}]
}
export class AssessmentMockDataService{
getAssessment(){
return Observable.of({});
}
}
上述组件的规格:
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ReactiveFormsModule, FormsModule],
declarations: [AssessmentComponent, QuestionsComponent],
providers: [
{ provide: AssessmentDataService, useClass: AssessmentMockDataService }
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AssessmentComponent);
let assessmentService: any = fixture.debugElement.injector.get(AssessmentDataService);
spyOn(assessmentService, 'getAssessmentQuestions').and.returnValue(Observable.of(assessmentMockData));
fixture.detectChanges();
});
当我运行ng test -sm=false 时,我得到了错误
错误::getAssessmentQuestions() 方法不存在
我在这里做错了什么?
【问题讨论】:
标签: angular unit-testing karma-jasmine