我有类来处理来自消防局的用户/auth操作。该服务工作正常,但当我尝试向服务添加测试时,如果出现错误,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
发布于 2020-01-04 06:01:45
我认为你在嘲笑FireAuthStub是不对的。它需要一个authState属性。
尝试将其设置为:
const FireAutStub = {
authState: new BehaviourSubject(true),
}现在,要将authState模拟为true和false,以供后续测试访问if或else可能是很棘手的。您可能需要将其与某种类型的主题关联起来,在其中您可以对其执行.next并控制其值。
https://stackoverflow.com/questions/59539023
复制相似问题