Angular2单元测试:测试组件的构造函数 [英] Angular2 unit testing : testing a component's constructor

查看:96
本文介绍了Angular2单元测试:测试组件的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

All is in the title : how can one test what is done in the component's constructor ?

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

For your information, I am using a service that requires a setting, and I would like to see if the 2 methods that I call in the constructor are called correctly.

我的组件的构造函数:

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);
  });
}


推荐答案

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

I would inject a fake service using the DI system, which would mean writing the tests something like this:

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();
    ...
  });
});

这允许您随时通过调用触发拖动事件。下一步,导致假服务上的订阅者被调用。然后,您可以对期望的结果进行断言。

This allows you to trigger "drag events" whenever you like by calling .next on the subject, which causes subscribers to the fields on the fake service to get called. You can then make assertions on the outcomes you expect from that.

请注意,您不需要调用构造函数你自己当DI系统实例化您的组件时,即调用 TestBed.createComponent 时,将调用此方法。

Note that you do not need to call constructor yourself; this method is invoked when the DI system instantiates your component, i.e. when TestBed.createComponent is called.

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

I would recommend that you don't spy on the component methods (e.g. this.onDrag) and just make sure that they get called, but rather test that whatever those methods should do as a result happens; this makes the tests more robust to changes in the specific implementation (I wrote a bit about this on my blog: http://blog.jonrshar.pe/2017/Apr/16/async-angular-tests.html).

这篇关于Angular2单元测试:测试组件的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆