Angular2:如何在ngOnInit()中向subscribe()提供数据?

时间:2017-03-11 03:08:07

标签: angular jasmine

我正在完成Angular2测试指南,并希望为ngOnInit()函数编写测试。

编程指南的Routing部分中的一个具有以下格式。数据来自解析器。当调用fixture.detectChanges()时,调用ngOnInit()。

let org: Org = null;
let savedOrg: Org = null;

...

ngOnInit(): void {
  let that = this;

  this.route.data
    .subscribe((data: { org: Org }) => {
      that.org = data.org;
      that.savedOrg = new Org(that.org);
  });
}

在我之前的问题中,我专注于通过解析器获取数据。用户" peeskillet"慷慨地给了我:

let routeStub: any = { data: org1 };

然而,这个(routeStub.data)是在ngOnInit()中看到的,并且我的代码因为没有调用subscribe()而失败,这不是我的存根中的。

(而不是通过大量更新对该问题着色,我决定创建这个新问题。)

实际上,我不想用mock来替换this.route.data的ngOnInit()版本。相反,我需要将数据传递给现有的this.route.data.subscribe()。

我该怎么做?

谢谢,

杰罗姆。

03/11更新解决方案

对我有用的只是与peeskillet推荐的略有不同。一,我的it()函数不使用其中的async()函数。二,我的routeStub observable需要一个命名属性" org",如Observable.of({' org':org1})。

以下是我在一个地方的工作代码:

let org1: Org = new Org({ ... details that fill it ... });
let routeStub: any = { data: Observable.of( { org: org1 } ) } ;

...

beforeEach(async(() => {
  TestBed.configureTestingModule({
    imports: [ FormsModule, RouterTestingModule ],
    providers : [
        { provide: ActivatedRoute, useValue: routeStub }          
    ],
    declarations: [ OrgDetailComponent ],
  })
  .compileComponents();
}));

beforeEach(() => {
  fixture = TestBed.createComponent(OrgDetailComponent);

  ...

});

it('should display original title', () => { 
  fixture.detectChanges();
  fixture.whenStable().then(() => {
    comp = fixture.componentInstance;
    de = fixture.debugElement.query(By.css('h2'));
    el = de.nativeElement;

    expect(comp.org).toEqual(org1);
    expect(el.textContent).toContain("Edit");
  });    
});

然后在组件中:

public ngOnInit(): void {
  let that = this;

  this.route.data
    .subscribe((data: { org: Org }) => {
      that.org = data.org;
    });
}

0 个答案:

没有答案
相关问题