Is it possible to write a unit test in ANgular that directly sends real http calls instead of mocking them?

I've been working on a monolithic Angular app and diving into the world of unit testing. I'm particularly focused on testing some services, and I keep coming across recommendations to mock http calls such as get and post. However, I'm not sure why this is necessary and if there's an alternative way to test without mocking. I've heard about using spies, but the concept is still unclear to me... My main goal is simply to ensure that certain http calls return the expected values. What is the most comprehensive approach I can take to achieve this? If you could explain it in the simplest terms possible or share any useful links on this topic, I would greatly appreciate it. Thank you! :)

Answer №1

If you're looking to conduct tests without mocking the API, it's more of an integration test rather than a unit test.

For Cypress: To quickly verify that your http calls are returning the expected values, Cypress is a great tool. Check out this tutorial to get started: . Essentially, you use cy.request and then make assertions about the anticipated data.

Postman: Another useful option for your scenario could be Postman:

Jasmine: You can also perform real requests using Jasmine:

 beforeEach(() => {
    ...
    TestBed.configureTestingModule({
      imports: [
        HttpModule // <-- simply provide the actual HttpModule here
      ]
    });

  });

  it('should do real requests', async(inject([Http], (http) => {
    http.get('your url').subscribe(res => {
      expect(res.json()).toBe(...);
    });
  })));

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

Scully on Angular failing to generate accurate HTML pages, lacking proper content and meta tags

Website Overview I recently created a user-friendly website called using Angular v14. My main objective now is to enhance the site's SEO and meta tags by implementing Scully v2.1.41. The entire process is handled on the front-end without the need fo ...

What is the process for obtaining the ID of a selected node within ngx-graph?

Issue My challenge lies in using the ngx-graph library to create a flow chart within Angular 9. I am attempting to extract the id value of a node that has been clicked on. I have tried printing out "$event" and examining the PointerEvent object that appea ...

The address :::3000 is already in use by NestJS

While attempting to deploy my NestJs server on a C-Panel hosting, I have encountered an issue. Despite properly installing all node_modules and ensuring every project file is in place, the server fails to start and continuously displays the following error ...

Tips for steering clear of distributive conditional types

Here's a breakdown of the different types: type Action<T> = T extends undefined ? { type: string; } : { type: string; payload: T; } type ApiResponse<T> = { ok: false; error: string; } | { ok: true; data: T; }; ...

Beneath the Surface: Exploring Visual Studio with NPM and Typescript

Can you explain how Visual Studio (2015) interacts with external tools such as NPM and the Typescript compiler (tsc.exe)? I imagine that during the building of a solution or project, MSBuild is prompted to execute these additional tools. I'm curious a ...

Remove a record from Angular 2 Firebase collection

I've been searching extensively for a solution to this problem. Despite following the documentation on AngularFire 2 and Angular 2, I am unable to find a working answer. My goal is simply to delete a specific entry in my Firebase database using its un ...

Angular service from an external package is experiencing issues with dependency injection where the HttpClient is returning

Imagine you are working with Angular and have the following custom libraries: The first library is a base service library: // base.service.ts import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core&apos ...

Guide to incorporating the useEffect hook within a React Native View

I am trying to use useEffect within a return statement (inside a Text element nested inside multiple View elements), and my understanding is that I need to use "{...}" syntax to indicate that the code written is actual JavaScript. However, when I implement ...

Struggling to design a versatile Angular Material dialog component for effortless reusability

I am currently working on developing a versatile Angular component that serves as a container for Material Angular dialogs. My aim is to be able to provide a child component or template to the container component and then utilize the MatDialog service to o ...

Are there advantages to incorporating d3.js through npm in an Angular 2 TypeScript project?

Summary: It is recommended to install d3.js via npm along with the typings. The accepted answer provides more details on this issue. This question was asked during my initial stages of learning Angular. The npm process is commonly used for tree-shaking, pa ...

Oops! An issue has occurred: Angular template is unable to read the property 'description' as it is undefined

This is my amazing service providing up-to-date information at your fingertips! fetchCurrentAffairs() : Observable<NewsData[]> { return this.httpClient.get<NewsData[]>(`${this.url}/latest`); } Introducing the brilliant component to brin ...

Angular2(Typescript) Http wrapper with RxJS observables and generic types

Today I faced a challenge while working on an abstract http service implementation. The goal of this service is to serve as a base for extending all other http services. Here's the current implementation, excluding some methods for illustration: @In ...

Tips for troubleshooting an Angular Service that is not properly injecting itself into the application

I offer a simple service: import { Injectable } from '@angular/core'; import { MdSnackBar, MdSnackBarConfig } from '@angular/material'; @Injectable() export class AlertsService { alerts: string[]; constructor(private snackBar: Md ...

Updating the value of a form control in Angular2

I am facing an issue when trying to create dynamic Angular 2 forms with controls and select boxes, like in this example on Plunker: <select class="form-control" ngControl="power"> <option *ngFor="#p of powers" [value]="p">{{p}}</o ...

How to add animations to individual items in an Angular list on click

Struggling to animate a single list item upon clicking, I realized the animation trigger is not being accessed in the onclick event code. A helpful solution I found while searching can be viewed here. <button mat-flat-button (click)="finishedChore ...

What is the best way to incorporate a class creation pattern in Typescript that allows one class to dynamically extend any other class based on certain conditions?

As I develop a package, the main base class acts as a proxy for other classes with members. This base class simply accepts a parameter in its constructor and serves as a funnel for passing on one class at a time when accessed by the user. The user can spe ...

The type 'ssr' is not found within the 'ResourcesConfig | LegacyConfig | AmplifyOutputs' interface. Error code: ts(2353)

I've been following a step-by-step tutorial (check it out here at 2:25:16) on creating a full stack application, but I've hit a roadblock when trying to enable SSR. import "@/styles/globals.css"; import type { AppProps } from "next ...

Testing Jasmine for a method that utilizes jQuery

In my controller, I have the following method: $scope.onWindowResize = function() { var dWidth= $('#div1').width(); var left = $('#div1').position().left; $('.myClass1').css({'width':dWdth}); $(&apos ...

Tips for centering an Angular mat prefix next to a label in a form field

Hey everyone, I need some help with aligning the prefix for an input with the mat label. Can anyone suggest a way to adjust the mat prefix so that it lines up perfectly with the mat label? Any assistance or ideas would be greatly appreciated. Here is the ...

Tips for testing a (Java) fluent API

Currently working on creating a Java fluent API similar to the one shown below: new Job().doFirst().doAfterFirst().thisOne(); new Job().doFirst().doAfterFirst().orThisOne(); To achieve this, I am defining various classes and interfaces as follows: publi ...