沿库

时间:2017-03-13 12:47:33

标签: angular testing typescript karma-runner

我已经将与websocket接口的交互抽象到自己的库中。该库提供单例服务来实现应用程序。

我现在正在尝试测试依赖于此库的组件。这是简化版和工作版:

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

为了概括测试文件并专注于小型独立测试,该库还会导出MessageServiceStub。但是,从.spec中删除MessageServiceStub并从库中导入它会导致以下错误:

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.

我已经研究过多种可能的解决方案(包括forwardRef'ing MessageServiceStub)而没有运气。虽然错误信息似乎足够明显,但其解决方案并非如此。

1 个答案:

答案 0 :(得分:0)

通过从各自的文件显式导入存根,可以避免这个问题:

使用

import { MessageService, WebsocketMessage } from 'messageLib/ng-websocket';
import { MessageServiceStub } from 'messageLib/lib/stubs/messageServiceStub';

而不是

import { MessageService, WebsocketMessage, MessageServiceStub } from 'messageLib/ng-websocket';