Unveiling the magic behind using jasmine to spy on a generic

I am trying to spy on a generic method in TypeScript, but Jasmine is not recognizing it.


Here is the code snippet:

http: HttpClient <- Not actual code, just showing type.
...
this.http.get<Customer[]>(url);

In this code, I am trying to mock the get<...> method.

const httpMock = {} as HttpClient;
spyOn(httpMock, 'get')
   .and.returnValue(of({} as Customer[]));

However, when I execute the test, I encounter the following error:

Error: : get() method does not exist
Usage: spyOn(, )

Answer №1

To resolve the issue, it was recommended not to utilize generics during mocking in the code.

describe('UserService', () => {
  it('should fetch correct users data', (done) => {

    const retrievedUsers = [...];

    const mock = {
      get: (_) => of({returnUsers}),
    } as HttpClient;

    const serviceUnderTest = new UserService(mock);

    //  Perform.
    serviceUnderTest.getUser()
        .subsribe(users => {

            //  Validate.
            ...

            done();
        });
  });
});

Answer №2

Initially, I want to mention that while HttpClientTestingModule exists, it may be unnecessary for simpler scenarios. By effectively mocking HttpClient using MockBuilder, like so:

beforeEach(() => {
  return MockBuilder()
    .keep(YourService)
    .mock(HttpClient);
});

Your code will function as intended.

spyOn(http, 'get').and.returnValue(of([] as Customer[]));

Note the use of [] instead of {}. It's advisable to employ a request object containing an array of items/rows along with other metadata for more realistic API responses.

If your application doesn't require any metadata, you can still utilize a pipe to convert to an array. This approach allows for easy modifications in the future.

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

Load a React component in the same spot when clicked

Is there a way to implement a functionality where clicking on different buttons in a panel will display different components in the same location? <AddNotification /> <EditNotification /> <DeleteNotification /> const AdminPanel = () =& ...

Updating an array by adding or removing items

I am attempting to create a method for deleting and adding items to an array, but I need easy-to-use delete and add methods since I am unfamiliar with TypeScript. export class NgForComponent implements OnInit { Numbers: number[]; constructor() { ...

Tips for tracking the evolution of changes to an array within React State

Experiencing challenges with saving the history of updates and modifications on a State. I have an object called "Journey" which includes a list of workshops (another array). Whenever I update my list of workshops, I aim to create a new array that captures ...

Having trouble getting the installed datejs typings to work properly

As I delve into Typescript due to my interest in Angular 2, I have come across the datejs Javascript library. To incorporate it into my Angular 2 project, I went ahead and installed datejs via npm, ensuring that it is correctly listed in my package.json. A ...

Create a package themed with Material UI for export

I am attempting to create a new npm package that exports all @material-ui/core components with my own theme. I am currently using TypeScript and Rollup, but encountering difficulties. Here is the code I have: index.ts export { Button } from '@materia ...

Receiving the error message 'Cannot find symbol Test' in Java using Selenium with TestNG

I am experiencing an issue with my TestNG setup where I am unable to run a test. The error message I am encountering can be seen here. After checking my POM.xml file for errors and reviewing the code in my test page, such as: import Pages.SearchPage; ...

The file path and installed npm package intellisense does not appear in VS Code until I press Ctrl + space for TypeScript

Before pressing ctrl + space, intellisense shows: click here for image description After pressing ctrl + space, intellisense displays: click here for image description Upon updating to vs code version 1.11.0 and opening my project, I encountered an issu ...

Strategies for mitigating the use of Observables when passing data between Angular routes

When trying to exchange data between routes, the most effective method appears to be using a service. To ensure that data is updated and re-rendered in the view, we are required to utilize BehaviorSubject. Based on my understanding, a simple component wou ...

The sequence of output in TypeScript when using Gulp is similar to running tsc with a tsconfig

After setting up a tsconfig file and successfully running the command-line tsc, I encountered an issue when using gulp-typescript with a tsconfig.json and outFile specified. The output ordering was different, and I have been unable to find a solution in Gu ...

Is there an alternative method to invoke the function aside from setTimeOut()?

if(i==1){ this.resetScreens(); this.editJobScreen1 = true; if(this.selectedLocations.length > 0){ this.locationService.getLocationByInput({ maxResultCount:16, skipCount: 0 }).subscribe((ele)=>{ ...

Having trouble getting the NextJS custom 404 page to display?

I've located the 404.tsx file in the apps/specificapp/pages/ directory, yet NextJS continues to show the default pre-generated 404 page. Could there be a misunderstanding on my part regarding the documentation, or is there some obstacle preventing me ...

It appears that using dedicated objects such as HttpParams or UrlSearchParams do not seem to work when dealing with Angular 5 and HTTP GET query parameters

I'm facing a perplexing issue that I just can’t seem to figure out. Below is the code snippet making a call to a REST endpoint: this.http.get<AllApplicationType[]>(environment.SUDS_API_SERVICE_URL + environment.SUDS_ALL_APPLICATIONS_URL, this ...

Steps to dynamically populate dropdown menus based on the selected options from other dropdown menus

I am working on a project that involves two dropdown menus. The options for the first dropdown menu are stored in a file called constant.ts. Depending on the selection made in the first dropdown, the options for the second dropdown will change accordingly. ...

Dealing with an iframe in Java using Selenium: Struggling with the .click() method issue

Transitioning from manual to automatic testing, I decided to start learning Selenium. While following a tutorial on a website, I encountered a cookie acceptance popup when launching the script and opening the test page. The advice was found within an ifra ...

Ways to retrieve data beyond the constructor

Here is the code snippet from my component.ts: export class OrganizationsComponent { public organizations; constructor(public access: OrganizationService) { this.access.getOrganizations().subscribe((data => { this.organizations = data; ...

The concept of RxJS's catchError function involves the return of a versatile

It's interesting that catchError is returning an Observable union type as Observable<{} | Page} instead of just Observable<Page>. The error message from the compiler reads: Type 'Observable<{} | Page>' is not assignable to t ...

A guide on incorporating typings for d3-tip in TypeScript 2.0

Seeking to implement tooltips in my charts using the d3-tip library. After installing typings for d3-tip in Typescript 2.0: npm install @types/d3-tip --save The typings appear in my package.json: "dependencies": { "@types/d3": "^4.7.0", "@types/d3- ...

Retrieving information using React Query in TypeScript

When working with React Query and TypeScript, I encountered an issue with the getRecommendations hook. I wanted to only send the latest recommendations (I may create another hook for watchlist items in the future). The error I received was related to the q ...

What is the best way to retrieve the final value stored?

This is how I am using my Selector:- private loadTree() { this.loading = true; this.store.select(transitionListSelector).pipe().subscribe(data => { console.log(data); data.map(item => { console.log(item); this.tr ...

Exploring the power of Django testing, managing transactions effectively, and automating browser

For my backend, I rely on django-rest-framework and for the frontend, I use angularjs. Recently, I started implementing e2e tests using protractor and encountered an issue where all changes in the database were being saved after each test. In django, eve ...