Search code examples
angularunit-testingservicekarma-jasmine

Spec has no expectations when unit testing a Service in Angular


So my tests are passing but it's this one unit test named should get the notes for the NoteService which, when ng test is ran, its name in Karma is written like

SPEC HAS NO EXPECTATIONS should get the notes

The method that I am trying to test is the following:

@Injectable()
export class NoteService {

  readonly baseUrl = "https://localhost:4200";
  readonly httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
    })
  };

  constructor(private httpClient: HttpClient) { }
 
  getNotes(): Observable<Note[]> {
    return this.httpClient.get<Note[]>(this.baseUrl + `/notes`, this.httpOptions);
  }

And the unit test is this:

describe('NoteService', () => {
  let service: NoteService;
  
  const mockList = [
    {
      "id": "id1",
      "title": "First note",
      "description": "This is the description for the first note",
      "categoryId": "1"
    },
    {
      "id": "id2",
      "title": "Second note",
      "description": "This is the description for the first note",
      "categoryId": "2"
    }]

beforeEach(() => {
    TestBed.configureTestingModule({imports: [HttpClientTestingModule], 
      providers: [NoteService]});
    service = TestBed.inject(NoteService);
  });

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

  it('should get the notes', fakeAsync(() => {
    service.getNotes().subscribe((val) => {
      expect(val).toBe(mockList);
    });
  }));
});

Therefore, why is it saying that "SPEC HAS NO EXPECTATIONS"? Is it something wrong with my unit test? And how should I tweak it in order to make it work well?


Solution

  • You don't need the fakeAsync here. You should be using done() to tell the test it's been finished:

    it('should get the notes',((done: DoneFN) => {
        service.getNotes().subscribe((val) => {
            expect(val).toBe(mockList);
            done();
        });
    }));