【问题标题】:Angular Unit test for an injected service注入服务的 Angular 单元测试
【发布时间】: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


    【解决方案1】:

    您需要在您的模拟中添加 getAssessmentQuestions(),因为它是在您的服务的 ngInit 中调用的。

    我猜你做对了,但随后将 getAssessment() 重命名为 getAssessmentQuestions() 并忘记在模拟中更改它。

    【讨论】:

    • 谢谢!但是,它说TypeError: Cannot read property 'unsubscribe' of undefined - 知道如何解决这个问题吗?
    • 不确定,但您订阅了 this._assessmentService,所以您需要取消订阅该服务,而不是我猜的评估订阅。
    猜你喜欢
    • 1970-01-01
    • 2016-05-29
    • 1970-01-01
    • 1970-01-01
    • 2020-11-20
    • 2017-11-19
    • 1970-01-01
    • 2019-05-06
    • 2016-12-21
    相关资源
    最近更新 更多