繁体   English   中英

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

[英]Unit testing a Service method subscribed to an Observable in Angular

我想使用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”

我不明白自己在做什么错...关于发生的事情有什么想法吗? 谢谢。

角度cli不再在每个角度之前增加第二个。

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

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

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

请尝试以下操作:

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();
  });
});

暂无
暂无

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

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