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

Connect ngx-time picker to form input in Angular

Currently, I have successfully implemented Angular material date pickers in my project, however, I am facing a challenge with integrating time pickers as it is not natively supported by Angular Material for version 8. To address this issue, I am utilizing ...

Ways to verify if a value corresponds to a particular data type

Is there a more elegant way for TypeScript to check if a value matches a specific type without actually invoking it, instead of the method described below? Consider the following example: import { OdbEventProcessorFunc } from "./OdbEventProcessor&quo ...

Implementing Firebase-triggered Push Notifications

Right now, I am working on an app that is built using IONIC 2 and Firebase. In my app, there is a main collection and I am curious to know if it’s doable to send push notifications to all users whenever a new item is added to the Firebase collection. I ...

When using Vue 3 in my app, I discovered that all the TypeScript files are easily accessible through the browser console

I recently completed my Vue3 js app with Typescript, and I have noticed that all the Typescript files are easily accessible for anyone to view through the Sources tab of the browser console. The code is perfectly clear and readable. Is there a method to p ...

Problem with selecting dates in rangepicker

Having trouble with my recursion code for selecting dates in a rangepicker: recurse( () => cy.get('.mantine-DatePicker-yearsListCell').invoke('text'), (n) => { if (!n.includes(year)) { //if year not f ...

Testing useEffect with React hooks, Jest, and Enzyme to add and remove event listeners on a ref

Here is a component I've been working on: export const DeviceModule = (props: Props) => { const [isTooltipVisible, changeTooltipVisibility] = useState(false) const deviceRef = useRef(null) useEffect(() => { if (deviceRef && dev ...

How to integrate a chips feature in Angular 4 using Typescript

Struggling to incorporate a chips component into my Angular web application, which comprises Typescript, HTML, and CSS files. After grappling with this for weeks without success, I have yet to find the right solution. To review my current code, you can a ...

Encountering intellisense problems while declaring or utilizing TypeScript types/interfaces within Vue.js Single File Component (SFC) documents

For my Nuxt 3 project, I am developing a component and attempting to declare an interface for the component props to ensure strong typings. Here is an example: <script setup> interface Props { float: number; } const props = defineProps<Props> ...

Is there a universal method to transform the four array values into an array of objects using JavaScript?

Looking to insert data from four array values into an array of objects in JavaScript? // Necessary input columnHeaders=['deviceName','Expected','Actual','Lost'] machine=['machine 1','machine 2&apo ...

In order to locate the xpath for the language dropdown menu on the Google sign-in page

Dropdown button on Signin page When the dropdown button is clicked, a list of languages is displayed. I am trying to store these languages in a list and then iterate through them using a for loop to select one. I have attempted various methods to create ...

Using React Material UI in Typescript to enhance the theme with custom properties

Struggling to customize the default interface of material ui Theme by adding a custom background property to palette. Fortunately, I found the solution thanks to this helpful shared by deewens. declare module '@material-ui/core/styles/createPalette& ...

Angular4 Leaflet Map encountering errors

Here is the template: <div id="mapid" style="height: 500px"></div> After installing Leaflet and the typings for Leaflet, I encountered an error stating that the map container was not found. To solve this, I added its import. This is the cont ...

What type is the appropriate choice for this handler?

I´m struggling to select the right type for this particular function. It serves as an async handler for express js in a project that utilizes typescript and eslint for linting with specific rules. export function asyncHandler( handler: any ): (req: Requ ...

Utilize localStorage.getItem() in conjunction with TypeScript to retrieve stored data

Within my codebase, I have the following line: const allGarments = teeMeasuresAverages || JSON.parse(localStorage.getItem("teeMeasuresAverages")) || teeMeasuresAveragesLocal; Unexpectedly, Typescript triggers an alert with this message: Argument ...

Making retries with the RetryWhen filter in Angular 2 RxJS Observables when encountering errors in the status

I'm currently working with the Angular 2 HTTP library, which returns an observable. I'm trying to set up a retry mechanism for specific error statuses/codes. The problem I'm facing is that when the error status is not 429, Observable.of(err ...

Compiling TypeScript: Using the `as` operator to convert and then destructure an array results in a compilation error, requiring an

I am currently utilizing TypeScript version 2.9.2. There is a static method in a third-party library called URI.js, which is declared as follows: joinPaths(...paths: (string | URI)[]): URI; I have a variable named urlPaths that is defined as urlPaths: s ...

Uh oh, it looks like there's an issue! The function getCoordinates is not recognized for this.locations

Whenever I attempt to execute the method in my class (getCoordinates()), an Error is thrown: ERROR TypeError: this.locations[0].getCoordinates is not a function What am I doing wrong? The service method I'm using: getLocations(){ return this ...

Working with TypeScript to set a value for an object's field

I have two objects of the same model: interface Project { _id?: string title: string description: string goal: string tasks?: Task[] createdAt?: Date updatedAt?: Date } The first object contains all fields from the interface, while the secon ...

Improve Observable to prevent type assertion errors

Currently working on writing unit tests for a CanDeactive Guard, encountering a type assertion error in my jasmine spec: // Mock Guard defined at the top of the spec file class MockGuardComponent implements ComponentCanDeactivate { // Adjust this value t ...

Tips for interfacing with Angular ColorPicker elements using Selenium WebDriver

Is there a way to automate interactions with Angular ColorPicker components using Selenium WebDriver? Since there is no text field input for hex codes, it relies solely on mouse clicks. For reference, you can check out this example: https://www.primeface ...