【问题标题】:Testing rxjs pipe operator in constructor在构造函数中测试 rxjs 管道运算符
【发布时间】:2019-12-31 02:46:43
【问题描述】:

我有类来处理来自 Firestore 的用户/身份验证操作。该服务正常工作,但是当我尝试向服务添加测试时,如果失败并出现错误TypeError: Cannot read property 'pipe' of undefined

这是我的服务

export class AuthService {
  user$: Observable<User>;

  constructor(private afAuth: AngularFireAuth, private afs: AngularFirestore) {
    this.user$ = this.afAuth.authState.pipe(
      switchMap(user => {
        if (user) {
          return this.afs.doc<User>(`user/${user.uid}`).valueChanges();
        } else {
          return of(null);
        }
      })
    );
  }
}

这是我对该类的规范文件的一部分

describe('AuthService', () => {
  beforeEach(() =>
    TestBed.configureTestingModule({
      providers: [
        { provide: AngularFireAuth, useValue: FireAutStub },
        { provide: AngularFirestore, useValue: FirestoreStub }
      ],
      imports: [AngularFireModule, AngularFireAuthModule]
    })
  );

  it('AuthService should be created', () => {
    const service: AuthService = TestBed.get(AuthService);
    expect(service).toBeTruthy();
  });
});

关于为什么测试抛出TypeError: Cannot read property 'pipe' of undefined 的任何想法,或者您有什么建议可以更好地测试它或使服务更“可测试”?

编辑: 这是 FireAutStub

const FireAutStub = {
  collection: (name: string) => ({
    doc: (_id: string) => ({
      valueChanges: () => new BehaviorSubject({ foo: 'bar' }),
      set: (_d: any) => new Promise((resolve, _reject) => resolve())
    })
  })
};

你可以在这里看到这两个课程https://gist.github.com/danielnv18/bfc5940f0bf078c77d895b5c34bf8a27

【问题讨论】:

  • 使用OnInit 而不是在构造函数中做事。否则,我猜你的存根不能正常工作,afAuth.authState 返回undefined。
  • 请分享你的FireAutStub类的源代码。
  • 如果 AuthService 确实是可注入的,则没有 ngOnInit 钩子。还是请分享 afAuth 类代码
  • 添加OnInit 不会有问题。根据angular.io/guide/lifecycle-hooks 仅适用于指令和组件。

标签: angular testing rxjs jasmine


【解决方案1】:

我认为你在错误地嘲笑 FireAuthStub。它需要一个 authState 属性。

尝试将其设置为:

 const FireAutStub = {
   authState: new BehaviourSubject(true),
 }

现在将 authState 模拟为 true 和 false 以便后续测试命中 if 或 else 可能会很棘手。您可能必须将其与某种类型的主题相关联,您可以在其中对其执行 .next 并控制其值。

【讨论】:

  • 谢谢。就是这样。我试图学习更多的角度测试
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-04
  • 1970-01-01
  • 1970-01-01
  • 2018-04-28
  • 1970-01-01
  • 1970-01-01
  • 2020-12-07
相关资源
最近更新 更多