TypeError:无法读取undefined属性'subscribe'(Angular Unit-Test)

问题描述 投票:0回答:1

我有一个简单的测试,结构如下:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { BreadcrumbsComponent } from './breadcrumbs.component';
import { RouterTestingModule } from '@angular/router/testing';
import { TranslateLoader, TranslateModule, TranslateService } from '@ngx-translate/core';
import { HttpClient } from '@angular/common/http';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { BreadcrumbsService } from './breadcrumbs.service';
import { multiTranslateHttpLoaderFactory } from 'app/app.component';

fdescribe('BreadcrumbsComponent', () => {
  let component: BreadcrumbsComponent;
  let translateService: TranslateService;
  let fixture: ComponentFixture<BreadcrumbsComponent>;
  let translateServiceStub: Partial<TranslateService>;


let translateServiceStub: Partial<TranslateService>;

translateServiceStub = {
  getBrowserLang: () => {
    return 'de';
  },
  onLangChange: new EventEmitter(),
};

breadcrumbsServiceStub = {
  onUpdateRequest: new Subject(),
  updateBreadcrumbs: () => {
  }
};

  beforeEach((() => {
    TestBed.configureTestingModule({
      declarations: [BreadcrumbsComponent],
      imports: [
        RouterTestingModule,
        HttpClientTestingModule,
        TranslateModule.forRoot({
          loader: {
            provide: TranslateLoader,
            useFactory: multiTranslateHttpLoaderFactory,
            deps: [HttpClient]
          }
        }),
      ],
      providers: [
        {provide: TranslateService, useValue: translateServiceStub},
        {provide: BreadcrumbsService, useValue: breadcrumbsServiceStub},
      ]
    });
  }));

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

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

目前抛出此错误,我无法处理:

TypeError:无法读取undefined的属性'subscribe'

这是我的类,ngOnInit方法中的一行会导致此错误:

export class BreadcrumbsComponent implements OnInit {

  breadcrumbs: Breadcrumb[] = [];

  constructor(private router: Router,
              private activeRoute: ActivatedRoute,
              private translate: TranslateService,
              private breadcrumbsService: BreadcrumbsService) {
  }

  ngOnInit() {
    this.translate.onLangChange.subscribe(() => this.identifyRoute());
  }

...

我在这做错了什么?要么。有没有办法绕过错误或模拟这一行,以便测试通过?我真的不知道如何在我的测试中模拟这一行。

angular unit-testing testing jasmine karma-jasmine
1个回答
0
投票

你能试一下吗:

import { of } from 'rxjs';

translateServiceStub = {
    getBrowserLang: () => {
       return 'de';
    },
    onLangChange: of({
       // whatever object is expected
     }),
 };
© www.soinside.com 2019 - 2024. All rights reserved.