Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

question from:https://stackoverflow.com/questions/66059460/spec-has-no-expectations-when-unit-testing-a-service-in-angular

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
846 views
Welcome To Ask or Share your Answers For Others

1 Answer

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();
    });
}));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...