0

I am going through some articles on unit testing and have found some pretty helpful examples. Most examples I am running across seem to be unit testing a function that does something with the Angular HttpClient and most look like this:

it('should return an Observable<User[]>', () => {
    const dummyUsers = [
      { login: 'John' },
      { login: 'Doe' }
    ];

    service.getUsers().subscribe(users => {
      expect(users.length).toBe(2);
      expect(users).toEqual(dummyUsers);
    });

    const req = httpMock.expectOne(`${service.API_URL}/users`);
    expect(req.request.method).toBe("GET");
    req.flush(dummyUsers);
  });

https://medium.com/netscape/testing-with-the-angular-httpclient-api-648203820712

This means that .getUsers() returns an observable. However, in my application, I am not returning an observable. Almost all of my HttpClient calls are similar to this:

async getCurrentUser(): Promise<UserInfo> {
     return await this._httpClient.get(`/api/me`).toPromise();
}

How do you go about unit testing the function calling the HttpPost or HttpGet within Karma?

Attempt:

  it('should get current user', async () => {
    const result = service.getCurrentUser();
    console.log('RESULT', result);
    const req = httpMock.expectOne(`/api/me`);
    const test = req.flush({test: 'ing'});
    console.log('REQUEST', test);

    expect('a').toEqual('a');
  });

1 Answer 1

1

I think I was overthinking it, but I managed to get it working by using .then rather than using await like I would in a normal (non-test) call:

it('should get current user', async () => {
    const response = new CustomResponseClass();
    response.success = true;
    response.error = null;
    const user = new User();
    user.userId = 1;
    user.name = 'Test User';
    response.data = user;
    service.getCurrentUser().then( _user => {
      console.log('USER', _user);
      // TODO: Some more unit tests here...
    });
    const req = httpMock.expectOne('/api/me');
    expect(req.request.method).toEqual('GET');
    req.flush(response);
  });
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.