angular - 注入(inject) MdDialogRef 的测试组件正在调用服务

标签 angular service jasmine mddialog testbed

我在测试具有 MdDialogRef 和注入(inject)服务的组件时遇到问题。我想测试该组件是否正在调用注入(inject)的服务。问题是我无法用通常的方式检索服务

fixture = TestBed.createComponent(...); 
component = fixture.componentInstance; 
service = fixture.debugElement.injector.get(Service);

因为必须像这样检索具有注入(inject) MDDialogRef 的组件:

dialog = TestBed.get(MdDialog);
dialogRef = dialog.open(CompanyLogoComponent);
component = dialogRef.componentInstance;

这是 MdDialogRef 的一种解决方法,它表示“没有可用于 MdDialogRef 的提供程序”,并且在提供需要许多参数时。 (也许有更好的方法来做到这一点然后使用固定装置?)

因此,没有可用的固定装置来检索服务...'debugElement.injector...'

当注入(inject)服务时,我有另一个作用域,因为 spy 没有反应:

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

知道如何将范围绑定(bind)到此处的组件或通过组件(dialogRef.componentInstance)检索服务吗?

最佳答案

我如何解决这个问题:

在TestComponent内部,注入(inject)MdDialog并设置dialogRef:

public dialogRef: MdDialogRef<TestComponent>;

constructor(private dialog: MdDialog, private service: TestService){}

在TestComponent.spec中,您可以像往常一样通过fixture获取TestService

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

要设置entryComponents,您可以覆盖BrowserDynamicTestingModule。

关于angular - 注入(inject) MdDialogRef 的测试组件正在调用服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42931441/

相关文章:

Windows 无法在 Windows Server 2008 SP1 上启动本地计算机上的服务错误 1067

android - 从 broadcastReceiver 调用服务中的函数

python - 我的守护进程启动后直接死掉

javascript - Jasmine 测试来自另一个目录中文件的 javascript

javascript - 在带有原型(prototype)的 Javascript 中使用此关键字?

Angular 5 全局查询参数

javascript - Angular 4 ngFor 设置元素的类

HTML <a> 从第二次点击开始跳转到页面的特定部分

javascript - 如果使用 jasmine 或 mocha 等测试框架时存在名为 "describe"或 "it"的全局函数怎么办

Angular HttpClient 没有返回我期望的对象