Unable to test a service method in angular using jasmine

I am doing unit testing in angular. In the component.ts, inside the ngOnInit, I have a service method call which I have shown below:

ngOnInit(){
   this.DomainManagementService.getVerifiedDomains().then(res => {
      this.claimedDomains = res.filter(domain => {
        return domain.status === 'claimed';
      });
    });
}

I am getting the data from the getVerifiedDomains() method and then applying filter method to filter out only the claimed domains. Finally I am storing the filtered domains in this.claimedDomains. Now I need to test whether the length of this.claimedDomains is greater than 0 or not. How to do this? Please help me to write the test case.

Upvotes: 0

Views: 148

Answers (2)

Thiago Prado
Thiago Prado

Reputation: 91

You need to do this to mock your service call:

// This will create a function that will inject the service in your test
function setup() {
    const domainManagementService = fixture.debugElement.injector.get(DomainManagementService);

    return { domainManagementService };
}

// - This is your test scenario
it('Load Claimed Domains ', () => {
    const { domainManagementService} = setup();
    spyOn(domainManagementService, 'getVerifiedDomains').and.returnValue(Promise.resolve([{status: 'claimed'},{status: 'claimed'}]));
    component.ngOnInit();
    expect(domainManagementService.getVerifiedDomains).toHaveBeenCalled();
    expect(component.claimedDomains.length).toBe(2);
});

But remember to mock your service response correctly so that you have the "claimedDomains" correct.

Upvotes: 1

AliF50
AliF50

Reputation: 18899

You have to first mock domainMainagementService, I would use jasmine.createSpyObj.

....
let mockDomainManagementService: jasmine.SpyObj<DomainManagementService>;
....
beforeEach(waitForAsync(() => {
   mockDomainManagementService = jasmine.createSpyObj<DomainManagementService>('DomainManagementService', ['getVerifiedDomains']);
   TestBed.configureTestingModule({
     ....
     providers: [{ provide: DomainManagementService, useValue: mockDomainManagementService }],
   }).compileComponents();
   // Make sure this is there before the first fixture.detectChanges().
   // The first fixture.detectChanges() calls ngOnInit.
   // Mock the return value here.
   mockDomainManagementService.getVerifiedDomains.and.returnValue(Promise.resolve([
     { status: 'claimed' },
  ]))
}));

it('should set claimedDomains', async () => {
   // wait until all promises are resolved with fixture.whenStable()
   await fixture.whenStable();
   expect(component.claimedDomains.length).toBe(1);
});

Upvotes: 1

Related Questions