Angular - No data received when subscribing to Observable

Currently, I am in the process of writing unit tests for a basic service. This service is responsible for fetching a list of users from the backend REST API.

// user.service.ts
import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {environment} from '../../../environments/environment';
import {ListDto} from '../../dto/commons/list.dto';

@Injectable()
export class UserService {

  constructor(
    private http: HttpClient
  ) { }

  getUserList(): Observable<ListDto> {
    return this.http
      .get<ListDto>(environment.coreUrl + environment.basePath + '/user');
  }

During my unit testing phase, I encountered an issue where there was no output when trying to log the Observable returned by the function getUserList(). As a result, I am unable to perform any validations. Below is the snippet of my unit test:

// user.service.spec.ts
import {UserService} from './user.service';
import {inject, TestBed} from '@angular/core/testing';
import {HttpClientTestingModule, HttpTestingController} from '@angular/common/http/testing';

describe('UserService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule
      ],
      providers: [
        UserService
      ]
    });
  });

  afterEach(inject([
    HttpTestingController
  ], (httpMock: HttpTestingController) => {
    httpMock.verify();
  }));

  it('should be able to get the list of users',
    inject(
      [HttpTestingController, UserService],
      (httpMock: HttpTestingController, service: UserService) => {
        service.getUserList().subscribe((data) => {
          console.log(data); // no output
        });
        // sanity
        const req = httpMock.expectOne('http://localhost:8080/v1/api/user');
        expect(req.request.method).toEqual('GET');
      }
    )
  );

Given that I am relatively new to Angular, I could use some guidance on where I might have gone wrong. Any assistance would be greatly appreciated.

Answer №1

It's important to note that there will be no response returned if you haven't instructed the mock Http Client to provide one.

To ensure a response, you must use req.flush(someTestData) as outlined in detail and demonstrated in the official guide.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountered issue while jasmine mocking angular $http - Error: describe function does not support a done parameter

I am currently working with an angular factory that looks like this: .factory('widgetFactory', ['$http', function($http){ function getWidgets(){ return $http.get('http://example.com/api/widgets/') .then(function(re ...

Utilizing the get and set methods to alter the structure of a string, but encountering the issue where the set method is

Upon receiving a datetime through an HTTP request, I need to format it before utilizing it. To achieve this, I utilize the get and set methods in my code. However, I noticed that the set method is never invoked. This is how my component (AdminComponent) l ...

Issues with Implementing Active Reports in Angular 8

Attempting to integrate Active Reports into Angular 8, I followed all the necessary steps outlined on this website: . However, upon compiling my application, I encountered the following error: ERROR in The target entry-point "@grapecity/activereports-angu ...

Is there a way to transform Observable<Observable<Organization>[]> into Observable<Organization[]>?

I have implemented ngrx/store in my project. .map((p: Observable<Organization>[]) => { return new usersActions.GetOrganizationSuccess(p); }) The GetOrganizationSuccess action is designed to accept Organization[] as the payload. Is ...

Integrating AngularJS code into dynamically generated HTML using JavaScript

I am currently utilizing an outdated version of AngularJS (1.3). I have a page where I need to dynamically display different content based on database values. If the user interacts with the page and changes the database value, I want the displayed content ...

Customize the text displayed in a dropdown menu in Angular Material based on the selection made

I am working with a multi-select dropdown menu that includes an option labeled "ALL" which, when selected, chooses all available options in the list. My goal is to display "ALL" in the view when this option is chosen or when the user manually selects all t ...

Having difficulty in utilizing localStorage to update the state

I've attempted to log back in using the stored credentials, however it's not working despite trying everything. The dispatch function is functioning properly with the form, but not when accessing localStorage. App.tsx : useEffect(() => { ...

I have an Observable but I need to convert it into a String

Seeking assistance with Angular translation service and Kendo.UI components. In the Kendo.UI documentation, it mentions the use of MessageService for component translation implementation. To achieve this, an abstract class must be extended containing a m ...

Tips for preventing the use of eval when invoking various functions

Here's a snippet of code I've been using that involves the use of eval. I opted for this approach as it seemed like the most straightforward way to trigger various factory functions, each responsible for different web service calls. I'm awa ...

AngularJS - Import and save CSV files

I have set up a nodeJS program as the server and an AngularJS web application as the client. For generating CSV files, I am utilizing the "express-csv" library (https://www.npmjs.com/package/express-csv) Below is the code for the server side: Definition ...

My variable from subscribe is inaccessible to Angular2's NgIf

My goal is to display a spinner on my application while the data is being loaded. To achieve this, I set a variable named IsBusy to True before making the service call, and once the call is complete, I set IsBusy to false. However, I am facing an issue wh ...

What is the best way to retrieve specific items from an array based on their attributes?

Is there a way to pull out objects from an Array that have a special attribute called "type" and assign them to the scope? I've been trying, but so far it hasn't worked for me. Any suggestions on how to accomplish this task? I attempted the foll ...

Updating bindings in AngularJS from promisesIn AngularJS, promises do not automatically update

I've encountered an issue with my promise implementation. After the promise resolves, the view doesn't update with the new value. Here's a small example in jsfiddle to demonstrate the problem: http://jsfiddle.net/58q8khap/8/ This is the vi ...

When trying to use an Angular filter to highlight text, an error about $sce being unsafe may still occur even when utilizing

I'm attempting to emphasize searched words by using an angular filter that dynamically adds span elements. Even though I am relying on the html with $sce, I keep encountering an error: Error: [$sce:unsafe] http://errors.angularjs.org/1.4.7/$sce/unsafe ...

How to access custom parameters set in middleware in Next.js server actions?

I'm currently utilizing middleware.ts to intercept and authenticate user requests. However, I want to include data from our database in these authenticated requests. Within my server action code, the structure is as follows: export async function get ...

Utilize AngularJS to upload Excel files and identify any potential issues with SOA APIs

Currently, I am encountering difficulties in uploading files through API calls. Unfortunately, I lack the necessary knowledge to resolve this issue. Is there anyone who can guide me on how to fix it? Here is my existing AngularJS code: <!DOCTYPE html ...

Is it possible to implement drag and drop functionality for uploading .ply, .stl, and .obj files in an angular application?

One problem I'm facing is uploading 3D models in angular, specifically files with the extensions .ply, .stl, and .obj. The ng2-upload plugin I'm currently using for drag'n'drop doesn't support these file types. When I upload a file ...

What is the best way to use hasClass in a conditional statement to display text based on the content of a different div element?

Let's say we have the following HTML code: <div>New York</div> Now, we want to add another div like this: <div>Free Delivery</div> How can we achieve this using JavaScript? ...

Specifying data type in the fetch method

Screenshot depicting fetch function I'm currently working on a project using Next.js with Typescript and trying to retrieve data from a Notion database. I've encountered an error related to setting up the type for the database_id value. Can anyon ...

Combining Rxjs map and filter to extract countries and their corresponding states from a JSON dataset

I have a unique dataset in JSON format that includes information about countries and states. For example: { "countries": [ { "id": 1, "name": "United States" }, { "id": 2, "name": "India" }], "states": [ { ...