Angular2单元测试:测试组件的构造函数

问题描述 投票:4回答:3

所有都在标题中:如何测试组件构造函数中的内容?

为了您的信息,我正在使用一个需要设置的服务,我想看看我在构造函数中调用的2个方法是否被正确调用。

我的组件的构造函数:

constructor(
  public router: Router,
  private profilService: ProfileService,
  private dragula: DragulaService,
  private alerter: AlertService
) {
  dragula.drag.subscribe((value) => {
    this.onDrag(value);
  });
  dragula.dragend.subscribe((value) => {
    this.onDragend(value);
  });
}
unit-testing angular angular2-testing
3个回答
9
投票

我会使用DI系统注入假服务,这意味着编写类似这样的测试:

describe('your component', () => {
  let fixture: ComponentFixture<YourComponent>;
  let fakeService;
  let dragSubject = new ReplaySubject(1);
  ...

  beforeEach(async(() => {
    fakeService = { 
      drag: dragSubject.asObservable(),
      ... 
    };

    TestBed.configureTestingModule({
      declarations: [YourComponent, ...],
      providers: [
        { provide: DragulaService, useValue: fakeService }, 
        ...
      ],
    });
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(YourComponent);
    fixture.detectChanges();
  });

  it('should do something when a drag event occurs', () => {
    dragSubject.next({ ... });
    fixture.detectChanges();
    ...
  });
});

这允许您通过在主题上调用.next来随时触发“拖动事件”,这会导致调用假服务上的字段的订阅者。然后,您可以对期望的结果进行断言。

请注意,您不需要自己致电constructor; DI系统实例化组件时调用此方法,即调用TestBed.createComponent时。

我建议你不要监视组件方法(例如this.onDrag)并确保它们被调用,而是测试那些方法应该做什么,结果发生;这使得测试对于特定实现的更改更加健壮(我在我的博客上写了一些关于这一点:http://blog.jonrshar.pe/2017/Apr/16/async-angular-tests.html)。


3
投票

在构造函数内部测试任何东西的简单方法是创建组件实例然后测试它。

it('should call initializer function in constructor', () => {
  TestBed.createComponent(HomeComponent); // this is the trigger of constructor method
 expect(sideNavService.initialize).toHaveBeenCalled(); // sample jasmine spy based test case
});

有一点需要注意,如果你想区分构造函数和ngOnInit,那么不要在fixture.detectChanges()中调用beforeEach()。而是在需要时手动调用。


0
投票

由于OP声明“我想看看我在构造函数中调用的2个方法是否被正确调用。”我有更好的方法。

写一个单元测试。您不需要使用测试台。它会大大减慢你的测试速度。手动实例化您的模拟。在您感兴趣的方法上设置间谍,然后使用您实例化的存根手动调用组件构造函数并设置间谍。然后测试是否正确调用了间谍方法。

关键是从原始服务类扩展存根。 jasmine.createSpyObj有助于模拟像Router这样的角度类。

© www.soinside.com 2019 - 2024. All rights reserved.