21

我有一个 angular 2 中的组件,它响应路由参数的变化(该组件不会从头开始重新加载,因为我们没有移出主路由。这是组件代码:

export class MyComponent{
    ngOnInit() {
        this._routeInfo.params.forEach((params: Params) => {
            if (params['area']){
                this._pageToShow =params['area'];
            }
        });
    }
}

这是一种享受,并且_pageToShow在导航上设置适当。

我正在尝试测试更改路线的行为(因此第二次触发可观察但它拒绝为我工作。)这是我的尝试:

it('sets PageToShow to new area if params.area is changed', fakeAsync(() => {
    let routes : Params[] = [{ 'area': "Terry" }];
    TestBed.overrideComponent(MyComponent, {
        set: {
            providers: [{ provide: ActivatedRoute,
                useValue: { 'params': Observable.from(routes)}}]
        }
    });

    let fixture = TestBed.createComponent(MyComponent);
    let comp = fixture.componentInstance;
    let route: ActivatedRoute = fixture.debugElement.injector.get(ActivatedRoute);
    comp.ngOnInit();

    expect(comp.PageToShow).toBe("Terry");
    routes.splice(2,0,{ 'area': "Billy" });

    fixture.detectChanges();
    expect(comp.PageToShow).toBe("Billy");
}));

TypeError: Cannot read property 'subscribe' of undefined但是当我运行它时会引发异常。如果我在没有这fixture.detectChanges();条线的情况下运行它,它会因为第二个期望失败而失败。

4

2 回答 2

32

首先,您应该使用 aSubject而不是Observable. observable 只被订阅一次。所以它只会发出第一组参数。使用 a Subject,您可以继续发送项目,并且单个订阅将继续获取它们。

let params: Subject<Params>;

beforeEach(() => {
  params = new Subject<Params>();
  TestBed.configureTestingModule({
    providers: [
      { provide: ActivatedRoute, useValue: { params: params }}
    ]
  })
})

然后在您的测试中使用params.next(newValue).

其次,您需要确保调用tick(). 这是如何fakeAsync工作的。您控制异步任务解析。由于 observable 是异步的,所以在我们发送事件的那一刻,它不会同步到达订阅者。所以我们需要强制同步行为tick()

这是一个完整的测试(Subject从导入'rxjs/Subject'

@Component({
  selector: 'test',
  template: `
  `
})
export class TestComponent implements OnInit {

  _pageToShow: string;

  constructor(private _route: ActivatedRoute) {
  }

  ngOnInit() {
    this._route.params.forEach((params: Params) => {
      if (params['area']) {
        this._pageToShow = params['area'];
      }
    });
  }
}

describe('TestComponent', () => {
  let fixture: ComponentFixture<TestComponent>;
  let component: TestComponent;
  let params: Subject<Params>;

  beforeEach(() => {
    params = new Subject<Params>();
    TestBed.configureTestingModule({
      declarations: [ TestComponent ],
      providers: [
        { provide: ActivatedRoute, useValue: { params: params } }
      ]
    });
    fixture = TestBed.createComponent(TestComponent);
    component = fixture.componentInstance;
  });

  it('should change on route param change', fakeAsync(() => {
    // this calls ngOnInit and we subscribe
    fixture.detectChanges();

    params.next({ 'area': 'Terry' });

    // tick to make sure the async observable resolves
    tick();

    expect(component._pageToShow).toBe('Terry');

    params.next({ 'area': 'Billy' });
    tick();

    expect(component._pageToShow).toBe('Billy');
  }));
});
于 2016-10-26T13:47:13.243 回答
6

我更喜欢像这样从 ActivatedRouteSnapshot 获取路由参数和数据this.route.snapshot.params['type']

如果你用同样的方法,你可以像这样测试它

1)在您的测试提供者中

{provide: ActivatedRoute, useValue: {snapshot: { params: { type: '' } }}}

2)在您的测试规范中

it('should...', () => {
   component.route.snapshot.params['type'] = 'test';
   fixture.detectChanges();
   // ...
});
于 2018-09-22T11:11:24.497 回答