简体   繁体   English

注入服务的角度单元测试

[英]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 当我运行ng test -sm=false ,出现错误

Error: : getAssessmentQuestions() method does not exist 错误:: getAssessmentQuestions()方法不存在

What am I doing wrong here? 我在这里做错了什么?

You need to add getAssessmentQuestions() in your mock, since it's called in the ngInit of your service. 您需要在模拟中添加getAssessmentQuestions() ,因为它是在服务的ngInit中调用的。

I guess you did it right but then rename getAssessment() to getAssessmentQuestions() and forgot to change it in the mock. 我猜你做对了,但是随后将getAssessment()重命名为getAssessmentQuestions() ,却忘记了在模拟中更改它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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