代码之家  ›  专栏  ›  技术社区  ›  Corcor

无法通过单元测试读取ngOnInit内部subscribe的未定义属性(读取'subscribe')

  •  0
  • Corcor  · 技术社区  · 3 年前

    当前面临单元测试错误:

    AppComponent > should call app
    TypeError: Cannot read properties of undefined (reading 'subscribe')
    

    在我的ngOnInit中,我有:

    this.eventsService.currentEvents.subscribe(events => {
      this.events = events;
      return this.processEvents(this.events);
    });
    

    失败的测试就在这里(这里称为ngOnInit):

      it(`should call app`, () => {
        const fixture = TestBed.createComponent(AppComponent);
        const app = fixture.debugElement.componentInstance;
        app.ngOnInit();
      });
    

    我的活动服务是:

    export class EventsService {
      constructor(private http: HttpClient, private store: Store<AppState>) {}
      
      private eventsSource = new BehaviorSubject<any>([]);
      currentEvents: Observable<any> = this.eventsSource .asObservable();
      
      getEvents(events: []) {
       this.eventsSource.next(events);
      }
    }
    

    应用程序。组成部分spec也有这样的设置:

      beforeEach(waitForAsync(() => {
        TestBed.configureTestingModule({
          imports: [RouterTestingModule, HttpClientModule],
          declarations: [AppComponent],
          providers: [
            { provide: EventsService , useValue: {
              getEvents: () => of([]),
              processEvents: () => of([])
            }},
            provideMockStore({}),
            { provide: Angulartics2, useValue: {} },
            { provide: Angulartics2GoogleAnalytics, useValue: { startTracking: () => {}} },
            { provide: WindowRef }
          ],
          schemas: [CUSTOM_ELEMENTS_SCHEMA]
        }).compileComponents();
      }));
    
      beforeEach(() => {
        eventService = TestBed.inject(EventsService);
        (<any>window).ga = jasmine.createSpy('ga');
      });
    
    1 回复  |  直到 3 年前
        1
  •  1
  •   random    3 年前

    EventService 提供者,添加服务属性 currentEvents

    providers: [
      {
        provide: EventsService, useValue: {
          getEvents: () => of([]),
          processEvents: () => of([]),
          currentEvents: of('events')
        }
      },
    ]