Do I have to inject the service in the unit test if I cal testBed.get() previously?

扶醉桌前 提交于 2019-12-24 00:46:07

问题


I have a service which I'm consuming in my angular 2 unit test.

I call the service in the beforeEach block first with TestBed.get()

Example:

 beforeEach(() => {
    fixture = TestBed.createComponent(ConfigComponent);
    component = fixture.componentInstance;
    service = TestBed.get(ConfigService);
    fixture.detectChanges();
  });

I then use this service in the unit test like this:

Example:

 it('should do something', inject([ConfigService], (configService) => {
      // code here
 }));

Do I need to inject the service in the unit test If called previously, or do I need to just call TestBed.get() and the use it across or should I do both?


回答1:


As it's explained in this answer, inject and TestBed.get are similar, so it's a matter of style. Some services that are common to all specs can be assigned to variables, while services that are specific to particular specs can be injected only in those specs.

In the case when spec function relies on inject and not local variables, it doesn't have to be necessarily defined in the scope of current describe block and can be reused or moved to some helper function.

It should be noticed that injector instance is created on first inject function or TestBed.get call, the way they are used can alter the results.



来源:https://stackoverflow.com/questions/47334855/do-i-have-to-inject-the-service-in-the-unit-test-if-i-cal-testbed-get-previous

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!