我是编写单元测试的新手,并试图找出为组件中的注入服务编写测试。
组件:
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()方法不存在
我在这里做错了什么?
答案 0 :(得分:1)
您需要在模拟中添加 getAssessmentQuestions(),因为它已在您服务的ngInit中调用。
我猜你做得对,但后来将 getAssessment()重命名为 getAssessmentQuestions(),忘了在模拟中更改它。