0

I am new to angular unit testing and I have tried to write test cases for service file. I need to write test cases for below code

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})

export class EmployeeDetailsService {
  private readonly employeeRoles = new BehaviorSubject<any>([]);
  private readonly isEmployeeData = new BehaviorSubject<boolean>(true);

  employeeRolesData = this.employeeRoles.asObservable();
  isEmployee = this.isEmployeeData.asObservable();

  addEmployeeRoles(data: string) {
    this.employeeRoles.next(data);
  }

  checkIsEmployee(data: boolean) {
    this.isEmployeeData.next(data);
  }
}

what I have tried is

import { TestBed } from '@angular/core/testing';
import { EmployeeDetailsService } from './EmployeeDetails.service';

describe('EmployeeDetailsService', () => {
    let service: EmployeeDetailsService;

    beforeEach(() => {
        TestBed.configureTestingModule({});
        service = TestBed.inject(EmployeeDetailsService);
    });

    it('should be created', () => {
        expect(service).toBeTruthy();
    });

    it('addEmployeeRoles', () => {
        service.addEmployeeRoles.subscribe(data => {
            expect(data).toEqual(data);
        })
    });

    it('checkIsEmployee', () => {
        service.checkIsEmployee.subscribe(data=>{
            expect(data).toEqual(data)
        })
    });

})

Unit test cases are passing, but code coverage is not improving. So please help me to solve this.

Sneha
  • 81
  • 1
  • 5

1 Answers1

0

The problem arise when you use expect in a subscribe. Since it's asynchronous, the expect can be executed after your test.

One of the way to solve this problem is to add a fuction that will be called inside the subscribe to notify Karma that your test is done like this:

it('checkIsEmployee', (done) => {
    service.checkIsEmployee.subscribe(data=>{
        expect(data).toEqual(data);
        done();
    })
});
JFPicard
  • 5,029
  • 3
  • 19
  • 43