在我的身份验证服务中,我正在从 angularFireAuth 调用一个名为 onAuthStateChanged 的函数。 文档将其描述为带有“更改时触发的回调”的 nextOrObserver。据我所知,当用户登录或注销时,onAuthStateChanged 将发出 firebase.User 对象或 null。
问题是,从单元测试的角度来看,我实际上并没有返回可观察的对象,因此我无法订阅它并在订阅中做出断言。
我能够监视“onAuthStateChanged”,但这只是我在代码中进行的测试。我不确定应该如何正确发出或模拟来自 onAuthStateChanged 的可观察响应,以便我可以测试逻辑分支。
单元测试功能
initialize(){
this.afAuth.onAuthStateChanged((user: User | null) => {
if (user) {
this.userData = {
uid: user.uid,
email: user.email,
emailVerified: user.emailVerified
};
this.liveUid = user.uid
if (typeof window !== 'undefined' && window.localStorage) {
localStorage.setItem('user', JSON.stringify(this.userData));
}
}
else {
this.userData = null
if (typeof window !== 'undefined' && window.localStorage) {
localStorage.setItem('user', 'null');
}
}
})
}
我的 angularFire 模拟
export const AngularFireAuthMock: any = {
const authState: User = {
uid: 'fakeuser',
email: '[email protected]',
emailVerified: true
};
onAuthStateChanged: () => {
return of(authState)
},
}
spect.ts
it('userData populated Successfully', fakeAsync(() => {
const spy = spyOn(AngularFireAuthMock, 'onAuthStateChanged').and.callThrough()
service.initialize()
expect(spy).toHaveBeenCalled()
console.log(service.userData)
}));
我想你只需要触发回调,这样你的模拟方法应该是这样的:
onAuthStateChanged: (callbackFn: (value: any) => void) => {
callbackFn(authState)
},