Experiment with a map function from RxJS within an HTTP request

Currently, I am in the process of testing an Angular service that includes a private mapper method. Upon review, it appears that this method has not been adequately tested for coverage. My objective is to create a mock for this method within the RxJS map function.

https://i.sstatic.net/T0jvp.png

During my Jest test, it seems that the method remains untested. Do you think I should consider mocking the private method?

 test('should test the download file', () => {
    const fakeurl = 'http://fakeurl';
    service.downloadFile(fakeurl).subscribe((resp: IDownload) => {
      expect(resp).toBe(mockDownloadedFile);
    });

    const req = httpMock.expectOne(request => request.url.includes(fakeurl), 'call api');
    expect(req.request.method).toBe('GET');
    req.flush(new Blob());
  });

Answer №1

It seems that due to the delay, the assertion within your subscribe function is not being executed.

To confirm that the assertions inside the subscribe block are indeed running, you can try the following:

it('should test the download file', () => {
    const fakeurl = 'http://fakeurl';
    service.downloadFile(fakeurl).subscribe((resp: IDownload) => {
      expect(1).toBe(2); // This test should fail
      expect(resp).toBe(mockDownloadedFile);
    });

    const req = httpMock.expectOne(request => request.url.includes(fakeurl), 'call api');
    expect(req.request.method).toBe('GET');
    req.flush(new Blob());

    subscripton.unsubscribe(); // Unsubscribe from the previous subscription
  });

Execute the above test and ensure that it fails to confirm that it is entering the subscribe block for assertions. If it passes, then it's likely not reaching that block.

In your specific scenario, utilizing fakeAsync could help in simulating time progression in a controlled manner:

import { fakeAsync, tick } from '@angular/core/testing';
....
it('should test the download file', fakeAsync(() => { // Include fakeAsync here
  const fakeurl = 'http://fakeurl';
  let response: IDownload;
  const subscription = service.downloadFile(fakeurl).subscribe((resp: IDownload) => {
    expect(1).toBe(2); // Ensure this fails and remove once failure is confirmed
    response = resp; // Assign response value here
  });

  const req = httpMock.expectOne(request => request.url.includes(fakeurl), 'call api');
  expect(req.request.method).toBe('GET');
  req.flush(new Blob());
  tick(3500); // Progress timer by 3500ms to bypass delay
  expect(response).toBe(mockDownloadedFile);
}));

Since you're using jest, there might be compatibility issues with using fakeAsync. Switching from test to it could potentially resolve this problem.

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

Angular2 does not load Js twice

I specified the path to my JS file in angular.cli. It loaded successfully during the initialization of the Angular app, but when navigating back to the component, it failed to load. Any suggestions on how to fix this issue would be greatly appreciated. Th ...

Troubleshooting font display problem in React Native when using the Poppins font for rendering Latin characters (ě, š, č, ř, ž) with <Font> tag

Currently, I am encountering a font rendering issue within my React Native project. Specifically, the problem arises with Latin letters such as ě, š, č, ř, ž when utilizing the Poppins font. Despite defining the font using the provided code snippet be ...

Utilize a string to access and sort the properties of a class in TypeScript

Let's discuss a simple problem involving objects in Javascript. Take for example an object like this: var obj={ par1:'value1', par2:'value2' } In JavaScript, we can access the values like obj['par1']. Now, the q ...

Tips for utilizing the randomColor library

Looking for guidance on incorporating the randomColor package from yarn to assign colors to various columns in a table within my project. Any examples or resources would be greatly appreciated! I am specifically working with React and Typescript. ...

RouterLink functionality stops working after the first click

Currently working on an Angular 4 project with a parent component A that contains a [routerlinkA] in the HTML, linking to component B. Component B then has another [routerlinkB] to return to A. Initially, everything functions perfectly. However, after mak ...

How can I utilize Angular services to transfer a count value to the Component?

I've been working on creating a coin counter for my application by developing a service specifically for counting coins. However, when I tried to use this service in one of my components where the count function is triggered, I encountered some diffic ...

When utilizing a Private Signed URL or Public URL from AWS S3, the Model Viewer for web fails to display the View in AR button

I integrated ModelViewer 1.9.2 by Google into my Angular project to display 3D models with surface detection for object augmentation. Initially, I successfully augmented 3D models from the application's assets. However, I'm facing issues when try ...

Refreshing the URL path with the chosen tab

Currently, I have a menu with multiple tabs and when a tab is clicked, the display content changes. Everything is working well, but I also want to update the URL path to reflect the selected tab. I'm looking for a way to modify my existing code to inc ...

How can I retrieve data during a double-click event in Kendo Grid using Angular?

How can I retrieve data on the doubleClick event in a Kendo Grid? I want to access the same object that is fetched during the selected event, which would be the dataitem at the selected index row. HTML: <kendo-grid #myGrid [data]="gridDat ...

Easily transferring sessionStorage values between components in Angular

I am looking for assistance on storing a user ID in sessionStorage and retrieving it in a blog component. Can anyone guide me on how to achieve this? LoginComponent.ts import { Component, OnInit } from '@angular/core'; import { Router, Activate ...

unable to access environment file

Recently, I delved into the world of TypeScript and created a simple mailer application. However, I encountered an issue where TypeScript was unable to read a file. Placing it in the src folder did not result in it being copied to dist during build. When I ...

Enforcing a discriminated union's match requirements

Challenging Situation I'm new to typescript and facing the task of converting the mapProps function provided below into typescript const addOne = x => x + 1 const upperCase = x => x.toUpperCase() const obj = { entry: 'legend', f ...

Exploring table iteration in Angular 7

I am looking to create a table with one property per cell, but I want each row to contain 4 cells before moving on to the next row... This is what I want: <table> <tr> <td> <mat-checkbox>1</mat-checkbox& ...

The Angular http.post function seems to be returning null responses consistently, without any actual data being received

When making a post call in Angular using Http.post, I am sending jsonData as a parameter with the following formatted data. However, every time I receive a response as null. Could you please review my code and let me know if there are any mistakes? Here ...

Troubleshooting Angular 2 routerLink functionality issues

I have gone through all the tutorials and still can't figure out what I am doing wrong. AppModule : import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } fr ...

Combining multiple arrays of objects using multiple keys with Angular 9 and Typescript

I have two JSON objects (displayed here with JSON.stringify(array of objects)) GPRows data is [ { "shopName":"Testing One", "state":"NSW", "yearMonth":"20203", "id& ...

Service in Angular 2 failing to push updates to component

I am currently working on a project where I need to retrieve data from MongoDB using a Service call. So far, the Service call is functioning correctly and logging the data in the console as expected. The challenge arises when dealing with a large response ...

Using Angular Material to link a constant within an HTML file

I have set up my constants in the following way: constants.ts export const Constants = Object.freeze({ ACCEPTED_LEADS_TO_CALL: "Accepted Leads to Call", RECOMMENDED_CALL_LIST: "Recommended Call List" }); This makes it easy to refere ...

Guide on displaying the length of an observable array in an Angular 2 template

I am working with an observable of type 'ICase' which retrieves data from a JSON file through a method in the service file. The template-service.ts file contains the following code: private _caseUrl = 'api/cases.json'; getCases(): Obs ...

Importing Angular libraries with the * symbol

One of the key modules in my library is sha256. To import it, I had to use the following syntax: import sha256 from 'sha256'; However, while researching this issue, I came across a question on Stack Overflow titled: Errors when using MomentJS ...