Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/32.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 注入MdDialogRef的测试组件正在调用服务_Angular_Service_Jasmine_Mddialog_Testbed - Fatal编程技术网

Angular 注入MdDialogRef的测试组件正在调用服务

Angular 注入MdDialogRef的测试组件正在调用服务,angular,service,jasmine,mddialog,testbed,Angular,Service,Jasmine,Mddialog,Testbed,我在测试使用MdDialogRef和注入服务的组件时遇到问题。我想测试这个组件是否正在调用注入服务。问题是我无法用通常的方法检索服务 fixture = TestBed.createComponent(...); component = fixture.componentInstance; service = fixture.debugElement.injector.get(Service); 因为具有注入MDDialogRef的组件必须按如下方式检索: dialog = TestBed

我在测试使用MdDialogRef和注入服务的组件时遇到问题。我想测试这个组件是否正在调用注入服务。问题是我无法用通常的方法检索服务

fixture = TestBed.createComponent(...); 
component = fixture.componentInstance; 
service = fixture.debugElement.injector.get(Service);
因为具有注入MDDialogRef的组件必须按如下方式检索:

dialog = TestBed.get(MdDialog);
dialogRef = dialog.open(CompanyLogoComponent);
component = dialogRef.componentInstance;
这是MdDialogRef的一个解决方案,它表示“没有可用于MdDialogRef的提供程序”,并且在提供需要的许多参数时。(也许有更好的方法来实现这一点,然后使用夹具?)

所以,没有可用的夹具来检索使用…“debugElement.injector…”的服务

注入服务时,我有另一个作用域,因为间谍不会做出反应:

it('method should call service', inject ([Service], (service: Service) =>  {
expect(service).toBeTruthy();
spyOn(service, 'method').and.callThrough();
component.methodCallingService();
expect(service.method).toHaveBeenCalled();
}));

你知道我如何在这里将作用域绑定到组件或通过组件(dialogRef.componentInstance)检索服务吗?

我如何解决这个问题:

在TestComponent内部,插入MdDialog并设置dialogRef:

public dialogRef: MdDialogRef<TestComponent>;

constructor(private dialog: MdDialog, private service: TestService){}
要设置entryComponents,可以覆盖BrowserDynamicTestingModule

    describe('TestComponent', () => {
    let component: TestComponent;
    let testService;
    let fixture;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        MaterialModule,
        MdDialogModule],
      declarations: [TestComponent],
      providers: [TestService]
    })
    .overrideModule(BrowserDynamicTestingModule, {
      set: {
        entryComponents: [TestComponent]
      }
    })
    .overrideComponent(TestComponent, {
    set: {
      providers: [
        {provide: TestService, useClass: MockTestService},
      ]
    }
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(TestComponent);
    component = fixture.componentInstance;
    companyService = fixture.debugElement.injector.get(TestComponent);
    fixture.detectChanges();
  });

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