Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 2在Karma Jasmine测试的父级中实例化全局注入器_Angular_Typescript_Karma Jasmine - Fatal编程技术网

Angular 2在Karma Jasmine测试的父级中实例化全局注入器

Angular 2在Karma Jasmine测试的父级中实例化全局注入器,angular,typescript,karma-jasmine,Angular,Typescript,Karma Jasmine,我有和这个帖子一样的设置 但是我无法在我的Karama Jasmine测试中使用ServiceLocator.inject.get-注入器为空 constructor() { this.inject = ServiceLocator.injector.get(InjectionService); this.configService = ServiceLocator.injector.get(ConfigService); } 在app.moudle模块中,我声明了以下内容

我有和这个帖子一样的设置

但是我无法在我的Karama Jasmine测试中使用ServiceLocator.inject.get-注入器为空

  constructor() {
    this.inject = ServiceLocator.injector.get(InjectionService);
    this.configService = ServiceLocator.injector.get(ConfigService);
}
在app.moudle模块中,我声明了以下内容,以便它在全球范围内可用

export class AppModule {
  constructor(private injector: Injector) {
    ServiceLocator.injector = this.injector;
  }
}
下面是我的测试设置的一个片段

describe('MyButtonComponent', () => {
  let component: MyButtonComponent;
  let fixture: ComponentFixture<MyButtonComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ButtonComponent, MyButtonComponent],
      providers: [SomeService,
        { provide: Router, useClass: RouterTestingModule },
        { provide: ServerService, useClass: GenericMock },
      ]
    })
      .overrideComponent(ResourceService, {
        set: {
          providers: [
            { provide: ConfigService, useClass: ConfigServiceMock }
          ]
        }
      })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(MyButtonComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

});

现在,当我运行测试ServiceLocator.injector时,它是空的。我如何让Karma Jasmin在父级中设置此设置,或者这是不可能的?

此全局注入器在角度上的移动值得怀疑,因为它使应用程序单元依赖于其他应用程序单元AppModule并破坏封装

基本上,它应该在单元测试中手动完成:

beforeEach(inject(injector: Injector) => {
  ServiceLocator.injector = injector;
}));
然后撤销:

afterEach(() => {
  ServiceLocator.injector = null;
});

更好的做法是将全局注入器移动到单独的模块,这样它就可以包含在测试台配置中。

@estus yours必须是与我不同的版本。下面的代码适用于我。但你让我走上了正轨,谢谢

  beforeEach(inject([Injector], (injector: Injector) => {
     ServiceLocator.injector = injector;
  }));

我正在努力让它工作。我得到了各种各样的错误,例如“,”预期的并且找不到名称“injector”,并且类型为“{ServiceLocator:any;}”的参数不能分配给类型为“number”的参数。Angular 8需要此语法版本