【发布时间】: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