How to mock AngularFire 2 service in unit test?

夙愿已清 提交于 2019-12-03 02:09:35
acdcjunior

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.

hope it is not off the topic, but the easiest solution I have found how to mock the FirebaseDatabase.

var object = function() {
      var obj = { valueChanges() {
            return of({data:'data'});     
        }
      }
      return obj;
    }

providers: [..., { provide : AngularFireDatabase,
        useValue: {object : object }} ]

instead of data:'data' you can mock whatever data you need. The functions can be modified as you wish.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!