单元测试在Angular中订阅Observable的Service方法

时间:2017-02-15 22:43:15

标签: unit-testing angular jasmine observable

我想使用Jasmine测试这个组件:

export class EditorComponent implements OnInit {
  movimiento: Movimiento;

  constructor(private route: ActivatedRoute, private datosService: DatosService) { }

  ngOnInit() {
    this.route.params
      .subscribe(params => {
        const _id = params['id'].toString(); // recepción del parámetro
        this.datosService
          .getMovimientoBy_Id$(_id)
          .subscribe(r => this.movimiento = r); // consulta al servicio
      });
  }

}

此方法订阅服务返回的Observable<Movement>。这是DatosService getMovimientoBy_Id$(_id)方法:

getMovimientoBy_Id$(_id): Observable<Movimiento> {
  return this.http
    .get(`priv/movimientos/${_id}`)
    .map(r => r.json());
}

我已经尝试过这段代码来测试组件:

describe('EditorComponent', () => {
  let movimiento = new Movimiento(new Date(), 0, 1, 1);
  let component: EditorComponent;
  let fixture: ComponentFixture<EditorComponent>;
  let datosService: DatosService;

  beforeEach(async(() => {
    let activatedRouteMock = {
      route: Observable.of({ id: 1 })
    }

    TestBed.configureTestingModule({
      imports: [
        HttpModule
      ],
      declarations: [
        EditorComponent
      ],
      providers: [
        DatosService,
        { provide: ActivatedRoute, useValue: activatedRouteMock }
      ]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(EditorComponent);
    component = fixture.componentInstance;
    datosService = fixture.debugElement.injector.get(DatosService);
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should create movimiento', (done) => {
    let spy = spyOn(datosService, 'getMovimientoBy_Id$').and.returnValue(Observable.of(movimiento));
    fixture.detectChanges();
    expect(component.movimiento).toBeTruthy();
    });
});

第一次测试通过,但在第二次测试中我得到了这个例外

  

未捕获错误:错误:0:0导致:无法读取未定义属性'subscribe'

我不明白我做错了什么......对于发生了什么的任何想法?感谢。

1 个答案:

答案 0 :(得分:1)

Angular cli在各自之前停止增加第二名。

 beforeEach(() => {
    fixture = TestBed.createComponent(EditorComponent);
    component = fixture.componentInstance;
    datosService = fixture.debugElement.injector.get(DatosService);
  });

这很有意义,因为您通常希望在开始测试之前模拟数据。

但实际问题是你如何模拟路由器。您需要添加路径属性参数,否则参数为空

请尝试以下操作:

describe('EditorComponent', () => {
  let movimiento = new Movimiento(new Date(), 0, 1, 1);


beforeEach(async(() => {
    let activatedRouteMock = {
      route: {
        params: {
          Observable.of({ id: 1 })
        }
      }
    }

    TestBed.configureTestingModule({
      imports: [
        HttpModule
      ],
      declarations: [
        EditorComponent
      ],
      providers: [
        DatosService,
        { provide: ActivatedRoute, useValue: activatedRouteMock }
      ]
    })
      .compileComponents();
  }));

  it('should create', () => {
    var component = fixture.componentInstance;
    expect(component).toBeTruthy();
  });

  it('should create movimiento', (done) => {
    var datosService = TestBed.get(DatosService);
    let spy = spyOn(datosService, 'getMovimientoBy_Id$').and.returnValue(Observable.of(movimiento));

    var fixture = TestBed.createComponent(EditorComponent);
    var component = fixture.componentInstance;
    fixture.detectChanges();
    expect(component.movimiento).toBeTruthy();
  });
});