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

7 unit-testing angular2-testing angular

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

为了您的信息,我正在使用一个需要设置的服务,我想看看我在构造函数中调用的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);
  });
}
Run Code Online (Sandbox Code Playgroud)

小智 12

在构造函数中测试任何东西的简单方法是创建组件实例,然后对其进行测试。

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
});
Run Code Online (Sandbox Code Playgroud)

需要注意的一点是,如果要区分构造函数和 ngOnInit,则不要调用fixture.detectChanges()inside beforeEach()。而是在需要时手动调用。


jon*_*rpe 11

我会使用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();
    ...
  });
});
Run Code Online (Sandbox Code Playgroud)

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

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

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

  • @trichetriche 不,我是说您通过确保服务上的事件与正确的行为挂钩来测试*构造函数的作用*。您*可以*简单地测试构造函数是否在虚假服务上的适当监视字段上调用`.subscribe`(例如执行类似`{drag: jasmine.createSpyObj('fake Drag event', ['subscribe']), ... }`),但这与当前的具体实现密切相关,而不是与您正在实现的实际功能密切相关。 (2认同)