是否可以列出组件依赖注入器的数组?

时间:2018-06-18 14:47:08

标签: javascript angular typescript karma-jasmine angular2-testing

如何以角度列出组件的所有依赖注入器?

此要求适用于单元测试。

我有一个按如下方式创建的组件实例:

component = fixture.componentInstance();

所以在我的测试用例中,我需要像

这样的东西

console.log(component.constructor.params) // should print all the constructor parameteres

以下代码中的ex:

constructor(private _logger: LoggerService, private _router: Router,
                private _adminService: AdminService) {
}

我需要获取DI的数组

0 -> LoggerService
1 -> Router
2 -> AdminService

3 个答案:

答案 0 :(得分:0)

您应该能够利用Javascript's built in arguments object.

因此,如果您只需要每个依赖项的类的名称,则可以将其放在构造函数中:

constructor(
    private _logger: LoggerService, 
    private _router: Router,
    private _adminService: AdminService
) {
    let dependencies = Array.from(arguments).map((item) => item.constructor.name);
}

dependencies对象登录到控制台应输出:

0: "LoggerService"
1: "Router"
2: "AdminService"

如果您的数组需要包含完整的对象而不是类的名称,只需从构造函数代码中删除.map()函数。

答案 1 :(得分:0)

您可以在注入依赖项之前先猴子对构造函数进行修补:

function keepConstructorDependenciesOf(MyClass) {
  // keep references to your class and your constructor
  const originalPrototype = MyClass.prototype;
  const originalConstructor = MyClass;

  // add the logic to retrieve the type of dependencies 
  MyClass = function() { 
    this.dependencies = Array.from(arguments).map(a => a.constructor.name); 
    originalConstructor.apply(this, arguments)  
  }

  // re-apply the original prototype
  MyClass.prototype = originalPrototype;

  return MyClass;
}

Component = keepConstructorDependenciesOf(Component);

// run the dependency injection
...

component = fixture.componentInstance();

expect(component.dependencies).toEqual([
  'LoggerService', 
  'Router', 
  'AdminService'
])

Some references about redefining a constuctor

答案 2 :(得分:-1)

使用此代码打印出构造函数参数。您必须在提供商处提及服务和路由器。

//import module services and router her 


 describe('MyComponent', () => {
  let _logger: LoggerService;
  let _router : Router;
  let _adminService :AdminService;
beforeEach(async(() => {

  TestBed.configureTestingModule({
    declarations: [
        MyComponent,
    ],
    imports: [ 
        CommonModule,
        FormsModule,
        HttpModule
  ],
  providers: [

  {provide:AdminService,  useValue: adminService},     
  {provide:Router, useValue:routerSpy} ,     
  {provide:LoggerService, useValue: logService } ,     

  ],
  }).compileComponents();

  fixture = TestBed.createComponent(MyComponent);
 component = fixture.componentInstance;
 _adminService = new AdminService(http);
  _logger = new LoggerService(http); 
}));  
    it('should create the app', async(() => {
      const fixture = TestBed.createComponent(MyComponent);
      component = fixture.componentInstance;
      const app = fixture.debugElement.componentInstance;
     console.log(component.constructor); 
    // should print all the constructor parameteres 
      expect(app).toBeTruthy();
    }));
}));