How to mock AngularFire 2 service in unit test?How SHOULD I inject document and window instances in angular2?How should I unit test threaded code?How do I test a private function or a class that has private methods, fields or inner classes?Unit Testing C CodeIs Unit Testing worth the effort?Unit test naming best practicesHow do you unit test private methods?JavaScript unit test tools for TDDWhat is Unit test, Integration Test, Smoke test, Regression Test?How to make mock to void methods with Mockitoshould angularFire2 access be through a service

Zeros of the Hadamard product of holomorphic functions

is it possible for a vehicle to be manufactured witout a catalitic converter

Using "subway" as name for London Underground?

Need feedback - Can the composition/colors of this design be fixed if something is lacking or is not a better fit?

How to tell your grandparent to not come to fetch you with their car?

A IP can traceroute to it, but can not ping

Cascading Switches. Will it affect performance?

Overlapping String-Blocks

Any way to create a link to a custom setting's "manage" page?

How do I prevent employees from either switching to competitors or opening their own business?

Applying Graph Theory to Linear Algebra (not the other way around)

Were Alexander the Great and Hephaestion lovers?

What ways have you found to get edits from non-LaTeX users?

Non-disclosure agreement in a small business

English word for "product of tinkering"

Is it a problem if <h4>, <h5> and <h6> are smaller than regular text?

Why doesn't Adrian Toomes give up Spider-Man's identity?

Why can't I use =default for default ctors with a member initializer list

SQL counting distinct over partition

Winning Strategy for the Magician and his Apprentice

Why didn't Voldemort recognize that Dumbledore was affected by his curse?

Do simulator games use a realistic trajectory to get into orbit?

Inward extrusion is not working

How to hide an urban landmark?



How to mock AngularFire 2 service in unit test?


How SHOULD I inject document and window instances in angular2?How should I unit test threaded code?How do I test a private function or a class that has private methods, fields or inner classes?Unit Testing C CodeIs Unit Testing worth the effort?Unit test naming best practicesHow do you unit test private methods?JavaScript unit test tools for TDDWhat is Unit test, Integration Test, Smoke test, Regression Test?How to make mock to void methods with Mockitoshould angularFire2 access be through a service






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








13















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';
import AngularFire, AuthProviders from 'angularfire2';

@Component(
moduleId: module.id,
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css']
)
export class AppComponent
isLoggedIn: boolean;

constructor(public af: AngularFire)
this.af.auth.subscribe(auth =>
if (auth)
this.isLoggedIn = true;
else
this.isLoggedIn = false;

);


loginWithFacebook()
this.af.auth.login(
provider: AuthProviders.Facebook
);


logout()
this.af.auth.logout();




All I'm doing is wrapping around the login and logout methods in AngularFire so I was thinking about using a mock to check if the methods were called but I'm not sure where to start, I tried doing the following in my spec file:



import provide from '@angular/core';
import AngularFire from 'angularfire2';
import
beforeEach, beforeEachProviders,
describe, xdescribe,
expect, it, xit,
async, inject
from '@angular/core/testing';
import AppComponent from './app.component';

spyOn(AngularFire, 'auth');

beforeEachProviders(() => [
AppComponent,
AngularFire
]);

describe('App Component', () =>
it('should create the app',
inject([AppComponent], (app: AppComponent) =>
expect(app).toBeTruthy();
)
);

it('should log user in',
inject([AppComponent], (app: AppComponent) =>
expect(app.fb.auth.login).toHaveBeenCalled();
)
);

it('should log user out',
inject([AppComponent], (app: AppComponent) =>
expect(app.fb.auth.logout).toHaveBeenCalled();
)
);
);


However I'm not sure how to mock the login and logout methods since they're part of the auth property, is there a way to mock auth and also the returning login and logout methods?










share|improve this question

















  • 3





    The interested reader should track this issue concerning making this less of a pain.

    – awqueous
    Nov 6 '16 at 19:41

















13















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';
import AngularFire, AuthProviders from 'angularfire2';

@Component(
moduleId: module.id,
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css']
)
export class AppComponent
isLoggedIn: boolean;

constructor(public af: AngularFire)
this.af.auth.subscribe(auth =>
if (auth)
this.isLoggedIn = true;
else
this.isLoggedIn = false;

);


loginWithFacebook()
this.af.auth.login(
provider: AuthProviders.Facebook
);


logout()
this.af.auth.logout();




All I'm doing is wrapping around the login and logout methods in AngularFire so I was thinking about using a mock to check if the methods were called but I'm not sure where to start, I tried doing the following in my spec file:



import provide from '@angular/core';
import AngularFire from 'angularfire2';
import
beforeEach, beforeEachProviders,
describe, xdescribe,
expect, it, xit,
async, inject
from '@angular/core/testing';
import AppComponent from './app.component';

spyOn(AngularFire, 'auth');

beforeEachProviders(() => [
AppComponent,
AngularFire
]);

describe('App Component', () =>
it('should create the app',
inject([AppComponent], (app: AppComponent) =>
expect(app).toBeTruthy();
)
);

it('should log user in',
inject([AppComponent], (app: AppComponent) =>
expect(app.fb.auth.login).toHaveBeenCalled();
)
);

it('should log user out',
inject([AppComponent], (app: AppComponent) =>
expect(app.fb.auth.logout).toHaveBeenCalled();
)
);
);


However I'm not sure how to mock the login and logout methods since they're part of the auth property, is there a way to mock auth and also the returning login and logout methods?










share|improve this question

















  • 3





    The interested reader should track this issue concerning making this less of a pain.

    – awqueous
    Nov 6 '16 at 19:41













13












13








13


4






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';
import AngularFire, AuthProviders from 'angularfire2';

@Component(
moduleId: module.id,
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css']
)
export class AppComponent
isLoggedIn: boolean;

constructor(public af: AngularFire)
this.af.auth.subscribe(auth =>
if (auth)
this.isLoggedIn = true;
else
this.isLoggedIn = false;

);


loginWithFacebook()
this.af.auth.login(
provider: AuthProviders.Facebook
);


logout()
this.af.auth.logout();




All I'm doing is wrapping around the login and logout methods in AngularFire so I was thinking about using a mock to check if the methods were called but I'm not sure where to start, I tried doing the following in my spec file:



import provide from '@angular/core';
import AngularFire from 'angularfire2';
import
beforeEach, beforeEachProviders,
describe, xdescribe,
expect, it, xit,
async, inject
from '@angular/core/testing';
import AppComponent from './app.component';

spyOn(AngularFire, 'auth');

beforeEachProviders(() => [
AppComponent,
AngularFire
]);

describe('App Component', () =>
it('should create the app',
inject([AppComponent], (app: AppComponent) =>
expect(app).toBeTruthy();
)
);

it('should log user in',
inject([AppComponent], (app: AppComponent) =>
expect(app.fb.auth.login).toHaveBeenCalled();
)
);

it('should log user out',
inject([AppComponent], (app: AppComponent) =>
expect(app.fb.auth.logout).toHaveBeenCalled();
)
);
);


However I'm not sure how to mock the login and logout methods since they're part of the auth property, is there a way to mock auth and also the returning login and logout methods?










share|improve this question














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';
import AngularFire, AuthProviders from 'angularfire2';

@Component(
moduleId: module.id,
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css']
)
export class AppComponent
isLoggedIn: boolean;

constructor(public af: AngularFire)
this.af.auth.subscribe(auth =>
if (auth)
this.isLoggedIn = true;
else
this.isLoggedIn = false;

);


loginWithFacebook()
this.af.auth.login(
provider: AuthProviders.Facebook
);


logout()
this.af.auth.logout();




All I'm doing is wrapping around the login and logout methods in AngularFire so I was thinking about using a mock to check if the methods were called but I'm not sure where to start, I tried doing the following in my spec file:



import provide from '@angular/core';
import AngularFire from 'angularfire2';
import
beforeEach, beforeEachProviders,
describe, xdescribe,
expect, it, xit,
async, inject
from '@angular/core/testing';
import AppComponent from './app.component';

spyOn(AngularFire, 'auth');

beforeEachProviders(() => [
AppComponent,
AngularFire
]);

describe('App Component', () =>
it('should create the app',
inject([AppComponent], (app: AppComponent) =>
expect(app).toBeTruthy();
)
);

it('should log user in',
inject([AppComponent], (app: AppComponent) =>
expect(app.fb.auth.login).toHaveBeenCalled();
)
);

it('should log user out',
inject([AppComponent], (app: AppComponent) =>
expect(app.fb.auth.logout).toHaveBeenCalled();
)
);
);


However I'm not sure how to mock the login and logout methods since they're part of the auth property, is there a way to mock auth and also the returning login and logout methods?







unit-testing angular jasmine karma-jasmine angularfire2






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jun 26 '16 at 20:36









Javier VillanuevaJavier Villanueva

1,793113571




1,793113571







  • 3





    The interested reader should track this issue concerning making this less of a pain.

    – awqueous
    Nov 6 '16 at 19:41












  • 3





    The interested reader should track this issue concerning making this less of a pain.

    – awqueous
    Nov 6 '16 at 19:41







3




3





The interested reader should track this issue concerning making this less of a pain.

– awqueous
Nov 6 '16 at 19:41





The interested reader should track this issue concerning making this less of a pain.

– awqueous
Nov 6 '16 at 19:41












2 Answers
2






active

oldest

votes


















14














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.






share|improve this answer
































    0














    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.






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f38042941%2fhow-to-mock-angularfire-2-service-in-unit-test%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      14














      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.






      share|improve this answer





























        14














        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.






        share|improve this answer



























          14












          14








          14







          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.






          share|improve this answer















          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.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jul 12 '16 at 17:40









          Splaktar

          2,82012256




          2,82012256










          answered Jun 26 '16 at 22:52









          acdcjunioracdcjunior

          85.8k23203201




          85.8k23203201























              0














              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.






              share|improve this answer



























                0














                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.






                share|improve this answer

























                  0












                  0








                  0







                  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.






                  share|improve this answer













                  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.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 24 at 18:16









                  JanJan

                  1




                  1



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f38042941%2fhow-to-mock-angularfire-2-service-in-unit-test%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                      용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

                      155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해