4

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?

Questieme
  • 913
  • 2
  • 15
  • 34

1 Answers1

8

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();
    });
}));
DonJuwe
  • 4,477
  • 3
  • 34
  • 59
  • 2
    Thanks! The thing is, I was using `done()` previously but gave me this error: `Error: Timeout - Async function did not complete within 5000ms (set by jasmine.DEFAULT_TIMEOUT_INTERVAL)`. Hence, I changed it to `fakeAsync` after digging up some answers. Therefore, how can I fix that timeout error that `done()` gives me? – Questieme Feb 05 '21 at 08:25
  • 1
    You have to mock `service.getNotes()` before and make it return an Observable. – DonJuwe Feb 05 '21 at 08:30
  • Thanks once again. Think you could help me out with an advice on how to do that? I am not sure if I should get rid of `TestBed` completely as shown in this post: https://stackoverflow.com/questions/58331328/how-to-mock-service-function-in-angular-component-for-unit-test – Questieme Feb 05 '21 at 08:36
  • try `spyOn(service, 'getNotes').and.returnValue(of(val))` – DonJuwe Feb 05 '21 at 09:05