角度单元测试:如何通过模拟http服务来检查是否已将项目添加到数组中

时间:2019-06-18 11:50:46

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

TodosComponent类==>

add() {
  var newTodo = { title: '... ' };
  this.service.add(newTodo).subscribe(
    t => {this.todos.push(t); alert();},
    err => this.message = err);
}

规范==>

it('should add new to do returned from the server', () => {
   let todo={id:1};
   let spy = spyOn(service, 'add').and.callFake(t => {
     return of([todo]);
   });
   component.add();
   console.log(component.todos); // 
   expect(component.todos.indexOf(todo)).toBeGreaterThan(-1); //always -1
});

控制台: enter image description here

0 个答案:

没有答案