lundi 13 mars 2017

Circular dependency when exporting a service stub along library

I have abstracted away interactions with a websocket interface into its own library. This library offers a singleton service to implementing applications.

I am now attempting to test a component that relies on this library. This is the reduced and working version:

imports (...)

class MessageServiceStub {
  private testData: WebsocketMessage =
  {
    'raw': new MessageEvent('type'),
    .....
  };
  public getMessageStream = (): any => {
    return Observable.of(this.testData);
  }
  public getStateStream = (): any => {
    return Observable.of(this.testData);
  }
}

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [LandingComponent],
      imports: [ClarityModule.forRoot(), ReactiveFormsModule]

    }).overrideComponent(LandingComponent, {
      set: {
        providers: [
          { provide: MessageService, useClass: MessageServiceStub },
        ]
      }
    }).compileComponents();
  }));

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

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

To generalize the test files and focus on small independent tests, the library also exports the MessageServiceStub. However, removing the MessageServiceStub from the .spec and importing it from the library instead causes the following error:

Error: Invalid provider for MessageService. useClass cannot be undefined.
           Usually it happens when:
           1. There's a circular dependency (might be caused by using index.ts (barrel) files).
           2. Class was used before it was declared. Use forwardRef in this case.

I have looked into multiple possible solutions (including forwardRef'ing MessageServiceStub) without luck. While the error message seems obvious enough, its solution is not.

Aucun commentaire:

Enregistrer un commentaire