在业力测试期间注入服务的属性未定义

时间:2018-03-06 16:47:02

标签: angular observable karma-jasmine

我正在尝试测试一个组件说 notificationComponent ,它有一个属性说 notes[] ,它会监听服务说 notificationService 有一个可观察的noteAdded,它广播发送给服务的所有通知。

我计划测试 notificationComponent 的方式是:每次将通知推送到 notificationService 时, notificationComponent 都应该填充{ {1}}通过听取 notificationComponent.notes[]

的函数

这是组件:

notificationService.noteAdded

NotificationService:     进口..

    import...;

    @Component({
      selector: 'app-notifications',
      templateUrl: './notifications.component.html',
      styleUrls: ['./notifications.component.css']
    })
    export class NotificationsComponent {

      notes: BentoAlertItemOptions[];

      constructor(private _notifications: NotificationsService) {
        this.notes = [];

        _notifications.noteAdded.subscribe(note => {
          this.notes.push(note);
        });
      }

      closeAlert($event:any) {
        console.info('Alert #', $event, ' is being closed');
      }
    }

这是我的spec文件:

@Injectable()
export class NotificationsService {
  private _notifications = new ReplaySubject<any>(5);
  public noteAdded = this._notifications.asObservable();

  constructor() {
    console.log("notification service constructor");
  }

  public add(notification: BentoAlertItemOptions) {
    console.log("added: ", notification);
    this._notifications.next(notification);
  }
}

虽然我在测试时遇到错误,但describe('NotificationsComponent', () => { let component: NotificationsComponent; let fixture: ComponentFixture<NotificationsComponent>; let testBedService:NotificationsService; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ NotificationsComponent, MockComponent({ selector: 'bento-alert', inputs: ['items'], outputs :['close'] }), ], providers: [ NotificationsService ] }) .compileComponents(); testBedService = TestBed.get(NotificationsService); })); beforeEach(() => { fixture = TestBed.createComponent(NotificationsComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); //THE TEST THAT FAILS fit('should push to notes[] for notes added event on the subscribed-service', () => { let addedNote:any; addedNote = { type :'success', msg : 'Moduled saved!', timeout : 2500, closeable: true } testBedService.add(addedNote); expect(true); }); }); 暗示cannot read property 'subscribe' of undefined未定义。

不确定为什么会发生这种情况,我也在使用测试中的真实服务,因为我不知道为什么我应该嘲笑像notificationComponent.notificationService.noteAdded这样的简单服务

1 个答案:

答案 0 :(得分:0)

我确实设法找到了发生的事情,似乎它不喜欢我嘲笑第三方便当组件:

 TestBed.configureTestingModule({
     declarations: [
            NotificationsComponent,
            MockComponent({
              selector: 'bento-alert',
              inputs: ['items'],
              outputs :['close']
            }),
          ],..

所以我导入了真正的模块而且工作正常:

 TestBed.configureTestingModule({
      declarations: [
        NotificationsComponent
      ],
      imports: [
        BentoModule
      ],..