danielnv18
danielnv18

Reputation: 45

Testing rxjs pipe operator in constructor

I have class to handle the user/auth operations from firestore. The service works correctly but when I try to add test to the service if fails with the error TypeError: Cannot read property 'pipe' of undefined

This is my service

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);
        }
      })
    );
  }
}

and this is part my spec file for that class

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();
  });
});

any ideas of why the testing is throwing TypeError: Cannot read property 'pipe' of undefined or do you have any suggestions to test it better o make the service more "testable"?

Edit: here's the the FireAutStub

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

and you can see both classes here https://gist.github.com/danielnv18/bfc5940f0bf078c77d895b5c34bf8a27

Upvotes: 0

Views: 273

Answers (1)

AliF50
AliF50

Reputation: 18849

I think you are mocking FireAuthStub incorrectly. It expects an authState property.

Try setting it to:

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

Now to mock authState to true and false for subsequent tests to hit the if or the else might be tricky. You might have to associate it to some type of subject where you can do .next on it and control its value.

Upvotes: 1

Related Questions