Ways to validate an HttpClient request

I have a HttpClient request that needs to be tested. Below is the test code I am using:

import { TestBed, inject } from '@angular/core/testing';

import { AviorBackendService } from './avior-backend.service';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { HttpEventType, HttpEvent } from '@angular/common/http';
import { User } from '../models/user.model';

describe('AviorBackendService', () => {
  let httpTestingController: HttpTestingController;
  let service: AviorBackendService;

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

   httpTestingController = TestBed.get(HttpTestingController);
   service = TestBed.get(AviorBackendService);
  });

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

  it('expects the service to fetch data with proper sorting', () => {
    console.log(service.SERVICE_URL);
    const mockResponse = [{
    _id: 25,
    loginId: 'string',
    lastname: 'string',
    firstname: 'string',
    password: 'string',
    eMail: 'string',
   } as User];

    /*  service.getUserCollection().subscribe(data => {
      expect(data.firstName).toEqual('Namehere');
    });  */
    // const req = httpTestingController
    // .expectOne(req => req.method === 'GET' && req.url === 'http://example.org');
    const req = httpTestingController.expectOne('http://localhost:3000/users');
    expect(req.request.method).toEqual('POST');
    console.log('REQ REQUEST URL:', req.request.url);
    // send the response to the subscribe.
    req.flush(mockResponse as any);
  });
});

The issue arises when running the req test which fails with the error

Error: Expected one matching request for criteria "Match URL: http://localhost:3000/users", found none.
. Additionally,
Property 'firstName' does not exist on type 'User[]'
triggers an error on
expect(data.firstName).toEqual('Namehere');
(which has been commented out). Attempts to troubleshoot following suggestions here were unsuccessful.

Here is my user-collection.model.ts:

import { User } from './user.model';

export interface UserCollection {

    user: User[];

}

And this is my user.model.ts:

import { Role } from './role';

// was class and not interface!
export interface User {
    _id: number;
    mandator?: number;
    loginId: string;
    lastname: string;
    firstname: string;
    password: string;
    eMail: string;
    group?: string;
    role?: Role;
    active?: boolean;
    token?: string;
}

Lastly, the backend code snippet:

export class AviorBackendService {
  readonly SERVICE_URL = 'http://localhost:3000/';
........
getUserCollection() {
    // withCredentials is very important as it passes the JWT cookie needed to authenticate
    return this.client.get<User[]>(this.SERVICE_URL + 'users', { withCredentials: true });
  }

Answer №1

If you uncomment the subscribe function, the expectOne method will work as expected.

it('checks if the service successfully retrieves sorted data', () => {
    const mockResponse = [{
    _id: 25,
    loginId: 'string',
    lastname: 'string',
    firstname: 'string',
    password: 'string',
    eMail: 'string',
   }];

    service.getUserCollection().subscribe(data => {
      expect(data[0].firstname).toEqual('string');
    });
    const req = httpTestingController.expectOne('http://localhost:3000/users');
    expect(req.request.method).toEqual('GET'); // Making sure it's a GET request
    // Provide the mocked response to the subscribe.
    req.flush(mockResponse);
  });

Answer №2

The property 'firstName' is not found in the type 'User[]'

Within the user class, the attribute for first name is written in lowercase. Please maintain consistency by changing 'firstName' to 'firstname'.

Kindly update the reference from firstName to firstname;

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

Intercept Axios Responses - Retrieving API Responses for HTTP Statuses that are not in the 200 range

I've set up a custom Axios instance with interceptors for handling responses. As per the Axios documentation, the success interceptor is triggered for 2xx statuses while the error interceptor handles any other status codes. My goal is to show an error ...

Unexpected behavior with Node js event listener

I am currently working on emitting and listening to specific events on different typescript classes. The first event is being listened to properly on the other class, but when I try to emit another event after a timeout of 10 seconds, it seems like the lis ...

What is the process for loading the chosen option JSON object from an array when a button is clicked?

I have a TypeScript file containing JSON objects that can be selected as options from a dropdown list. I am looking for guidance on how to load/instantiate the selected JSON object when the user clicks a button to proceed. Specifically, I would like to le ...

Discover the data type of a class attribute's accessor methods in TypeScript

Since TypeScript 4.3 introduced the ability for class properties to have getters and setters of different types since 4.3, I am unsure how to correctly retrieve the types of a property's getter and setter. === Since a class property is treated as a ...

Emulating Data in Angular 2 Using Configuration Similar to Ember Mirage

Is there a way to mock data through configuration in Angular 2 similar to how it's done in Ember Mirage? I'm aware that I can create my own solution using Dependency Injection and MockBackend to intercept HTTP calls and provide dummy data. Howeve ...

In Typescript with Vue.JS, the type 'Users[]' does not include the essential properties of type 'ArrayConstructor' such as isArray, prototype, from, of, and [Symbol.species]

Embarking on my journey with typescript and vuejs, I stumbled upon a perplexing error that has halted my progress for the past 48 hours. The error message reads as: Type 'Users[]' is missing the following properties from type 'ArrayConstruct ...

Can the width of an offcanvas panel be adjusted?

Currently implementing the offcanvas component in my project, but I'm looking to make the panel wider than the standard size. Specifically, I want it to be 35% width. I've attempted to utilize the panelClass NgbOffcanvasOptions property, however, ...

Strategies for enhancing performance in an Angular 4 project

Currently, I am engaged in a project that involves utilizing Angular 4 for the front-end and PHP for the back-end with the support of an Apache server on Ubuntu 16.04 LTS. We have incorporated Node JS to facilitate the functionality of Angular. This raises ...

A step-by-step guide on reversing options in the Ant Design Cascader component

By default, the Cascader component's options are nested from left to right. I am looking to have them go from right to left instead. However, I could not find anything in the component's API that allows for this customization. Is it even possibl ...

What is the proper way to transmit JSON data to a node.js server using the fetch API in JavaScript

I am currently working with a node.js back-end server and Angular 10 on the front-end. I need to pass data from the front-end to the back-end using fetch. This is my front-end code: testmariadb($event: MouseEvent) { return fetch('/api/customQuery ...

The namespace does not contain any exported member

Every time I attempt to code this in TypeScript, an error pops up stating The namespace Bar does not have a member named Qux exported. What could possibly be causing this and how can I resolve it? class Foo {} namespace Bar { export const Qux = Foo ...

What is the best way to extract a specific value from a JSON object?

I'm currently working on building a marketplace using Angular. The main marketplace page is already set up and populated with data from a remote JSON file created with mockapi. However, I've encountered an issue when trying to display a single ra ...

Type definition for Vuex store functionality

Working on creating a versatile type to provide typing hints for mutations in Vuex. After reading an inspiring article on Vuex + TypeScript, I decided to develop something more generic. Here is what I came up with: export type MutationType<S, P, K exten ...

Can the base href in Angular be dynamically changed during runtime?

Within my single Angular application, I have set the base-href to /a/b/. This means that in my dist folder, there is an HTML file with <base href="/a/b/">. As a result, the browser recognizes that an image link like assets/images/logo.png can be foun ...

The failure to build was due to the absence of the export of ParsedQs from express-serve-static-core

Encountered the error message [@types/express]-Type 'P' is not assignable to type 'ParamsArray'. Resolved it by installing specific packages "@types/express": "^4.17.8", "@types/express-serve-static-core": ...

Struggling to implement a singleton service in Angular as per the documentation provided

I have implemented a service in Angular that I want to be a singleton. Following the guidelines provided in the official documentation, I have set the providedIn property to "root" as shown below: @Injectable({ providedIn: "root" }) export class SecuritySe ...

Applying ngClass to a row in an Angular material table

Is there a way I can utilize the select-option in an Angular select element to alter the css-class of a specific row within an Angular Material table? I have successfully implemented my selection functionality, where I am able to mark a planet as "selecte ...

A guide on sorting data by chosen tab using mat-tab in Angular

I'm currently exploring ways to filter data based on the selected tab's value using mat-tab. You can find more information about it here. For example, I aim to create a tab panel with three tabs representing cities: ALL, LA, and SF. If a user cli ...

angular 2 : Unable to locate the variable named 'Response'

I encountered an issue while working on my angular 2 project: Error: Cannot find name 'Response'. The error seemed to originate from the following service: import { Injectable } from '@angular/core'; import { Http } from '@ang ...

Tips for embedding HTML/CSS snippets in backticks when using TypeScript with AngularJS

Does anyone else experience the issue of their Angular 2 templates showing up as gray text in Visual Studio Code? I'm unable to use autocomplete or see my CSS properly. Is this a settings problem or is there a plugin that can solve this? BTW, I am us ...