karma TypeError“无法读取未定义的属性'subscribe'”

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了karma TypeError“无法读取未定义的属性'subscribe'”相关的知识,希望对你有一定的参考价值。

在测试具有共享服务的简单组件时,会出现以下错误消息,并且我无法使其工作,我已经尝试了所有内容!

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

lr.component.ts

export class LrComponent implements OnDestroy {
  currentRouter: string;
  private subscription: Subscription;

  constructor(private lrService: LrService) {
    this.subscription = this.lrService.lrNavigation$.subscribe(
      (currentNav: string) => {
        this.currentRouter = currentNav;
      },
      (error) => {
        console.warn(error);
      }
    );
  }

  ngOnDestroy() {
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
  }
}

lr.service.ts

@Injectable()
export class LrService {
  // Observables for our components to subscribe to.
  lrNavigation$: Observable<string>;

  // Subjects to return data to subscribed components
  private lrNavigationSubject = new Subject<string>();

  constructor() {
    this.lrNavigation$ = this.lrNavigationSubject.asObservable();
  }

  // Triggers subscribed components
  lrNavigate(currentNav: string) {
    this.lrNavigationSubject.next(currentNav);
  }
}

任何-random.component.ts

// In another component we send the string that we want the subscribed component (LrComponent) to receieve
this.lrService.lrNavigate('LR');

lr.component.spec.ts

class MockRouter {
  navigate = jasmine.createSpy('navigate');
}

class MockActivatedRoute {
  params = jasmine.createSpy('params');
}

class MockLrService extends LrService {
  lrNavigation$: Observable<string> = new Subject<string>().asObservable();

  constructor() {
    super();
  }

  lrNavigate(currentRouter: string) {
    return Observable.of(['LR']);
  }
}

export function main() {
  describe('LrComponent', () => {
    let fixture: ComponentFixture<LrComponent>;
    let component: LrComponent;
    let lrService: LrService;

    beforeEach(async(() => {
      TestBed.configureTestingModule({
        declarations: [
          LrComponent,
          LrMappingsComponent,
          LrCategoriesComponent,
        ],
        imports: [
          RouterTestingModule,
          CommonModule,
          LrRoutingModule,
          SharedModule,
          AgGridModule.withComponents(
            [
              CaseSensitiveFilterComponent,
              ButtonComponent,
              ColumnHeaderComponent,
              TypeaheadEditorComponent,
              ButtonGroupComponent
            ]
          )
        ],
        providers: [
          { provide: LrService, useClass: MockLrService },
          { provide: Router, useClass: MockRouter },
          { provide: ActivatedRoute, useClass: MockActivatedRoute },
        ]
      }).compileComponents();
    }));

    beforeEach(() => {
      fixture = TestBed.createComponent(LrComponent);
      component = fixture.componentInstance;
      lrService = fixture.debugElement.injector.get(LrService);
    });

    it('should create LrComponent', () => {
      fixture.detectChanges();
      expect(component).toBeDefined();
    });

    it('should have the current router set', async(() => {
      fixture.detectChanges();
      expect(component.currentRouter).toEqual('LR', 'the data should be `LR`');
    }));
  });
}

错误

enter image description here

注意:

如果我只使用Jasmine,没有Angular测试框架的东西,它可以工作。但这不是我想测试@Component的方式。

例:

export function main() {
  describe('LrComponent', () => {
    let fixture: ComponentFixture<LrComponent>;
    let component: LrComponent;
    let lrService: LrService;

    beforeEach(() => {
      lrService = new MockLrService();
      component = new LrComponent(lrService);
    });

    it('should create LrComponent', () => {
      fixture.detectChanges();
      expect(component).toBeDefined();
    });
  });
}

这有效,但不是我想要的。

有关如何解决这个问题的任何线索?我真的尝试过很多东西但都没有用......

答案

好吧,如果有人面临同样的问题,我会自己回答。

结果是删除:

{ provide: Router, useClass: MockRouter }

解决了这个问题。我真的不知道为什么。我确信服务中的Observables存在一些问题......

这些依赖是因为这个:

it('should be able to navigate through tabs',
      fakeAsync((inject([Router, Location], (router: Router, location: Location) => {
        router.initialNavigation();

        let tabLinks, a1, a2;
        fixture.detectChanges();

        tabLinks = fixture.debugElement.queryAll(By.css('a.mappings'));
        a1 = tabLinks[0];
        a2 = tabLinks[1];


        a1.triggerEventHandler('click', { button: 0 });
        tick();
        expect(location.path()).toEqual('lrMappings');

        a2.nativeElement.click();
        tick();
        expect(location.path()).toEqual('categories');
      }))));

但是,将它们从providers中删除并注入它们就像这里显示的那样可以使它工作。

以上是关于karma TypeError“无法读取未定义的属性'subscribe'”的主要内容,如果未能解决你的问题,请参考以下文章

调度操作并从同一组件中的 redux 获取状态的最佳实践?

将变量传递给按钮 vue js laravel

TypeError:无法分配给只读属性 - Karma

Karma 测试 Angular - TypeError:无法读取 null 的属性“recipientAddressId”

[karma-server]:TypeError:无法读取未定义的属性“范围”-CI 环境中的 Angular 单元测试

Angular Karma - TypeError:无法读取未定义的属性“_id”