Search code examples
angulartypescripttestingmethodsget

Angular: Unit testing GET method in service


I have a service method that returns item and unit test for the get method. However, the coverage shows that the getter method is not covered. Can you suggest what am I doing wrong in unit test?

export class ItemService{
#item: Item;
  get item(): Item{
    return this.#item;
  }
}
import itemMock from '../mocks/item-response.json';
describe('ItemService', () => {
  let itemService: ItemService;
  it('should get item information', () => {
      itemService['#item'] = itemMock ;
      spyOnProperty(itemService, 'item').and.returnValue(itemMock);
      expect(itemService['#item']).toEqual(itemMock );
  });
}

Solution

  • Ok, so I think the problem is your spy is actually replacing the getter, and this one is never called. Maybe you could change strategy and only check on the private property without Spy ?