Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 AngularFire Auth testing with Jasmine

I'm trying to write a unit test for my Component, but I can't spy on the AngularFire class correctly.

//Component

  import { AngularFire } from 'angularfire2';

  @Component({
    selector: 'app-header',
    templateUrl: './header.component.html',
    styleUrls: ['./header.component.scss']
  })
  export class HeaderComponent implements OnInit {

    constructor(
      public angularFire: AngularFire
    ) { }

    ngOnInit() {
      this.angularFire.auth.subscribe(auth => {
        // do stuff
      });
    }
  }

My test is simple, I'm trying to spy on the Auth class to turn the subscribed mock user.

//Test
let AngularFireMocks = {
  auth: jasmine.createSpy('auth')
};

AngularFireMock.auth.and.returnValue(Observable.of({ uid: 'ABC123' }));

describe('HeaderComponent', () => {
  let component: HeaderComponent;
  let fixture: ComponentFixture<HeaderComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        HeaderComponent
      ],
      providers: [
        {
          provide: AngularFire,
          useValue: AngularFireMocks
        }
      ],
      imports: [
        AngularFireModule.initializeApp(environment.firebase)
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(HeaderComponent);
    fixture.detectChanges();
  });
});

I get the error;

this.angularFire.auth.subscribe is not a function

I don't understand why, I used this same kind of logic when testing an async service, but when doing the same for a component it doesn't appear to work.

I've also tried returning different types of observables - like using Observable.create instead of Observable.of as well as mocking out the auth class and spying on the subscribe function and returning an object, but it doesn't seem to work.

like image 550
sketchthat Avatar asked Nov 28 '25 20:11

sketchthat


1 Answers

I think the problem is that auth isn't called as a function (auth()), it's accessed as a property. and.returnValue probably only works on functions (and when the function is called). You could make it work by just doing

let AngularFireMocks = {
  auth: Observable.of({ uid: 'ABC123' })
};

and just forget the spy.

like image 148
Paul Samsotha Avatar answered Dec 01 '25 12:12

Paul Samsotha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!