首页 文章

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

提问于
浏览
4

全部在 Headers 中: how can one test what is done in the component's constructor ?

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

3 回答

  • 0

    我会使用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 来随时触发"drag events",这会导致调用假服务上的字段的订阅者 . 然后,您可以对期望的结果进行断言 .

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

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

  • 8

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

    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,那么不要在 beforeEach() 内调用 fixture.detectChanges() . 而是在需要时手动调用 .

  • 3

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

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

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

相关问题