【问题标题】:how to test function inside if statement jasmin karma angular如何在if语句中测试函数jasmine karma angular
【发布时间】:2019-03-13 09:44:34
【问题描述】:

我是单元测试的新手。 我有一个组件调用服务来显示学生列表。

 getListStudents() {
this.noteService.getStudents({}).subscribe(res => {
  this.students= res
})}

然后我在 ngOnInit() 中调用这个函数

 if(this.currentUser.Type == 'Teacher'){
this.getListStudents()
}

如果没有 if 语句,测试是正确的,但如果有 if 语句,它就坏了

这是我的测试

  it('should call the service  getStudents', () => {
component.currentUser={ "Type": "Teacher"}
let mock = [{
  "ID": 22,
  "name": "paul"
}]
let service: NoteService = TestBed.get(NoteService);
  spyOn(service, 'getListStudents').and.returnValue(of(mock));
  fixture.detectChanges();
  expect(component.students.length).toBe(1)
 });

我收到错误无法读取 null 的属性“类型”,当我从 ngOnInit 中删除 if 语句时,它按预期工作我做错了什么? 请建议我解决此问题的解决方案。谢谢

【问题讨论】:

  • 也许你可以在定义 component.currentUser 之后使用fixture.detectChanges(); ?我希望它有所帮助。
  • 感谢您的回答 =) ,但我仍然得到 component.students.length=0
  • 尝试在 beforeEach 语句中定义component.currentUser={ "Type": "Teacher"}。它对我有用。
  • 再次感谢您的回答=)它在fixture.detectChanges()之后坏了;我得到错误 TypeError: Cannot read property 'Type' of null
  • 你需要在 constructor() 中初始化 currentUser 属性

标签: angular unit-testing karma-jasmine karma-runner angular7


【解决方案1】:

使用同步测试,as shown in the docs

it('should call the service  getStudents', fakeAsync(() => {
  component.currentUser={ "Type": "Teacher"}
  let mock = [{
    "ID": 22,
    "name": "paul"
  }]
  let service: NoteService = TestBed.get(NoteService);
  spyOn(service, 'getListStudents').and.returnValue(of(mock));
  fixture.detectChanges();
  tick();
  expect(component.students.length).toBe(1)
}));

【讨论】:

  • 感谢您的回答 =) 在 fixture.detectChanges(); 之后它坏了我得到错误 TypeError: Cannot read property 'Type' of null
  • 这意味着你在某处写了this.currentUser = null
  • 我的 spec.ts 中只有一个测试,我调用了 component.currentUser={ "Type": "Teacher"} 我不明白为什么 null 以及当我在测试它包含教师
  • 您的组件可能会更改该值。 null 是一个非常具体的值,不能隐式使用:如果它为空,那么您可能将其设置在某个地方!
  • 我应该在构造函数()中初始化 currentUser 属性,这是错误 =)谢谢你的帮助和时间 trichetriche
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
  • 2015-12-07
  • 1970-01-01
  • 1970-01-01
  • 2018-01-31
  • 1970-01-01
相关资源
最近更新 更多