Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking BsModalRef for Unit Testing

I am using the BsModalRef for showing modals and sending data using the content property. So we have some like this :

this.followerService.getFollowers(this.bsModalRef.content.channelId).subscribe((followers) => {
    this.followerList = followers;
    this.followerList.forEach((follower) => {
      follower.avatarLink = this.setUserImage(follower.userId);
      this.followerEmails.push(follower.email);
    });
  });

We are setting the channelId in content of bsModalRef (this.bsModalRef.content.channelId). It is working fine. Now i am writing a unit test for this. Problem is i am not able to mock it. I have tried overriding, spy etc but nothing seems to work. I am using the approach mentioned in this link. One alternative is to use TestBed but i am not much aware of its use. Can anyone please help me finding any approach by which this can be achieved ?

like image 259
G.S Abhaypal Avatar asked May 09 '18 08:05

G.S Abhaypal


1 Answers

I recently had to do something similar and Mocking the method call worked. The tricky part is injecting the BsModalService in both the test suite and the component.

describe('MyFollowerService', () => {
    configureTestSuite(() => {
        TestBed.configureTestingModule({
            imports: [...],
            declarations: [...],
            providers: [...]
        }).compileComponents();
    });

    // inject the service
    beforeEach(() => {    
        bsModalService = getTestBed().get(BsModalService);
    }


    it('test', () => {
       // Mock the method call 
       bsModalService.show = (): BsModalRef => {
           return {hide: null, content: {channelId: 123}, setClass: null};
       };

       // Do the test that calls the modal

    });
});

As long as you're calling bsModal as follows this approach will work

let bsModalRef = this.modalService.show(MyChannelModalComponent));

Finally, here are some links that have more indepth coverage about setting up the tests with TestBed.

  • https://chariotsolutions.com/blog/post/testing-angular-2-0-x-services-http-jasmine-karma/
  • http://angulartestingquickstart.com/
  • https://angular.io/guide/testing
like image 131
Justin Wrobel Avatar answered Nov 14 '22 10:11

Justin Wrobel