为什么 BehaviourSubjects 的 `combineLatest` 上的 `.pipe` 未定义?

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

在 Angular 10 应用程序中,我有一个服务类:

@Injectable()
export class MyService {
  private readonly bSubject1$: BehaviorSubject<SomeType[]> = new BehaviorSubject<SomeType[]>(null);
  private readonly bSubject2$: BehaviorSubject<AnotherType[]> = new BehaviorSubject<AnotherType[]>(null);
  private readonly bSubject3$: BehaviorSubject<LastType[]> = new BehaviorSubject<LastType[]>(null);
  
  private readonly subscription$: Observable<SomeType[]>;
  private readonly bs4$: BehaviorSubject<string> = new BehaviorSubject<string>('');
  private readonly bs5$ = new BehaviorSubject<boolean>(false);

  constructor(router: Router) {
    this.subscription$ = this.createStructure();

    router.events
      .pipe(filter((event) => event instanceof NavigationEnd))
      .subscribe((event: NavigationEnd) => {
        console.log('some code here');
      });
  }

  private createStructure() {
    const sub$ = combineLatest([this.bSubject1$, this.bSubject2$, this.bSubject3$])
      .pipe(filter(...), map(...)); // Failed: Cannot read properties of undefined (reading 'pipe')

    return combineLatest([sub$, this.bs4$, this.bs5$])
      .pipe(map(...));
  }

}

我正在尝试这样测试:

export class RouterMock {}

describe('MyService', () => {
  let service: MyService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        { provide: Router, useClass: RouterMock },
        { provide: MyService, useClass: service },
      ],
    });

    service = TestBed.inject(MyService);
  });

  it('should create', () => {
    console.log('service', service);  // service is logged as `undefined`
    expect(service).toBeTruthy();
  });

});

测试在第一个

pipe
上失败并带有
Failed: Cannot read properties of undefined (reading 'pipe')
(用注释突出显示)。

我在测试模拟中缺少什么?

angular testing service rxjs jasmine
1个回答
0
投票

尝试进行模拟服务导入(

Dep1Service
)并为“我的服务”提供适当的服务

export class Dep1ServiceMock {}

describe('MyService', () => {
  let service: MyService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        { provide: Dep1Service, useClass: Dep1ServiceMock },
        MyService,
      ],
    });

    service = TestBed.inject(MyService);
  });

  it('should create', () => {
    console.log('service', service);  // service is logged as `undefined`
    expect(service).toBeTruthy();
  });

});
© www.soinside.com 2019 - 2024. All rights reserved.