简体   繁体   中英

Angular Unit test for an injected service

I'm new to writing unit tests and trying to figure out writing a test for an injected service in a component.

Component:

constructor(private _assessmentService: AssessmentDataService){

}

ngOnInit(){
    const assessmentSub: Subscription = this._assessmentService.getAssessmentQuestions().subscribe(responseData => {
        const obj = responseData.assessment;
        assessmentSub.unsubscribe();
    });
}

Service:

getAssessmentQuestions(){
    return this._http.get('./assets/data/data.json').map(response => response.json());
}

Mock Service:

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({});
    }
}

Spec on the above component:

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();
  });

When I run ng test -sm=false , I get the error

Error: : getAssessmentQuestions() method does not exist

What am I doing wrong here?

You need to add getAssessmentQuestions() in your mock, since it's called in the ngInit of your service.

I guess you did it right but then rename getAssessment() to getAssessmentQuestions() and forgot to change it in the mock.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM