How to mock AngularFire 2 service in unit test?

前端 未结 3 1832
情话喂你
情话喂你 2021-02-05 12:14

I\'m trying to set up unit tests for a sample Angular 2 app using AngularFire 2 auth, the component is fairly simple:

import { Component } from \'@angular/core\'         


        
3条回答
  •  星月不相逢
    2021-02-05 12:41

    In this snippet:

    beforeEach(() => addProviders([
      AppComponent,
      AngularFire
    ]);
    

    You set (or override) the providers that will be used in your test.

    That being said, you can create a different class, a mock if you will, and, using the { provide: originalClass, useClass: fakeClass } notation, provide it instead of the AngularFire actual class.

    Something like this:

    class AngularFireAuthMock extends AngularFireAuth {           // added this class
      public login() { ... }
      public logout() { ... }
    }
    
    class AngularFireMock extends AngularFire {                   // added this class
      public auth: AngularFireAuthMock;
    }
    
    beforeEach(() => addProviders([
      AppComponent,
      { provide: AngularFire, useClass: AngularFireMock }         // changed this line
    ]);
    

    And the AngularFires in your tests will be AngularFireMocks.

提交回复
热议问题