Skip to content

Instantly share code, notes, and snippets.

@danielnv18
Created December 31, 2019 02:42
Show Gist options
  • Save danielnv18/bfc5940f0bf078c77d895b5c34bf8a27 to your computer and use it in GitHub Desktop.
Save danielnv18/bfc5940f0bf078c77d895b5c34bf8a27 to your computer and use it in GitHub Desktop.
import { TestBed } from '@angular/core/testing';
import { AngularFireAuth } from '@angular/fire/auth';
import { AngularFirestore } from '@angular/fire/firestore';
import { BehaviorSubject } from 'rxjs';
import { AngularFireModule } from '@angular/fire';
import { AngularFireAuthModule } from '@angular/fire/auth';
import { AuthService } from './auth.service';
const FirestoreStub = {
collection: (name: string) => ({
doc: (_id: string) => ({
valueChanges: () => new BehaviorSubject({ foo: 'bar' }),
set: (_d: any) => new Promise((resolve, _reject) => resolve())
})
})
};
const FireAutStub = {
collection: (name: string) => ({
doc: (_id: string) => ({
valueChanges: () => new BehaviorSubject({ foo: 'bar' }),
set: (_d: any) => new Promise((resolve, _reject) => resolve())
})
})
};
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();
});
});
import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import { AngularFirestore } from '@angular/fire/firestore';
import { Observable, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { User } from '@app/core/interfaces';
@Injectable({
providedIn: 'root'
})
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);
}
})
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment