Encountering a "then is not a function" error when attempting to mock an HTTP promise service

Unique service

fetchPopupData(Docversion, versionname, Structureweek, docVersionFieldID, versionid, WLTP) {
        return this.http.get(this.apiUrl + 'GetElementPopUpData?docVersion=' + Docversion + '&versionVariant=' + versionname
            + '&structureWeek=' + Structureweek + '&docVersionFieldID=' + docVersionFieldID
            + ' &VersionId=' + versionid + ' &isWLTP=' + WLTP, { withCredentials: true })
            .toPromise().then(response => <CoCCreateVersionPopupPage[]>response.json())
            .catch(error => {
                return error;
            });
    }

Using the unique service in component

this.popupService.fetchPopupData(this.docInfo.version,
            this.docInfo.versionName,
            this.docInfo.week, this.docInfo.fieldID, this.docInfo.id,
            this.docInfo.WLTP)
            .then(
            data=> { ...});

Simulated service using constructor injection

fetchPopupData(Docversion, versionname, Structureweek, docVersionFieldID, versionid, WLTP) {
        return Observable.of({ Result: {} });
    }

An error occurred during testing of the method

TypeError: this.popupService.fetchPopupData(...).then is not a function

I understand the cause of the error - I am using Observable in my simulated service while the actual service relies on promise, causing issues with the then callback. Please advise on how to create a simulated service for an http promise service call.

Answer №1

Which testing framework do you prefer to use?

To conduct tests, I often employ the spy technique using Jasmine:

spyOn(createversionservice, 'getVersionDataValuesforPopup')

This allows you to verify if your function was invoked.

If you need to return a promise, you can utilize the .andReturnValue() method as demonstrated below:

var promise = Promise.resolve('result');
spyOn(createversionservice, 'getVersionDataValuesforPopup').andReturnValue(promise);

Equivalent methods exist in various other testing frameworks as well.

You can then assert that the method was called (or any other desired test) like so:

expect(createversionservice.getVersionDataValuesforPopup).toHaveBeenCalled()

Answer №2

Could you kindly attempt the following:

create a new Promise that resolves to an empty object
return new Promise((resolve) => { resolve({}); });

Answer №3

I was able to fix the issue by implementing the following code:

Promise.resolve({then: jest.fn()})

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

Xtermjs does not support copying and pasting functionalities

I'm struggling to enable the copy & paste feature in my terminal using xterm.js APIs. My goal is to allow users to copy strings from the clipboard. Currently, I have implemented the following code: this.term.onKey((key) => { if (key.domEven ...

Is it possible to initiate a request action in both the constructor and ngOnInit method?

I am facing a situation where I need to trigger a request action from both the constructor and ngOnInit functions in order to load data. However, I have noticed that on the second call, one of the dispatch actions is not being invoked and the data remains ...

Generating a default template for an Angular ag-Grid cell with a custom field name - how to do it?

I am currently working with ag-grid and have specific templates for many columns. However, some of the data I am inputting into the table are just plain text. I want to enhance the default case: <ng-template #defaultRecord let-record> ADDITIONAL E ...

Dev error occurs due to a change in Angular2 pipe causing the message "has changed after it was checked"

I understand the reason for this error being thrown, but I am struggling with organizing my code to resolve it. Here is the problem: @Component({ selector: 'article', templateUrl: 'article.html', moduleId: module.id, di ...

Discovering a specific property of an object within an array using Typescript

My task involves retrieving an employer's ID based on their name from a list of employers. The function below is used to fetch the list of employers from another API. getEmployers(): void { this.employersService.getEmployers().subscribe((employer ...

Include various classes within the [ngclass] directive

I tried researching on SO for a solution to the following query, but I am having trouble understanding how to implement it correctly. The goal is to display a delete icon when hovering over a mat td cell, but this icon should only appear for newly added va ...

The parameter type 'IScriptEditorProps' does not accept arguments of type 'string'

After trying numerous solutions, I decided to integrate this script editor into a SharePoint site. However, when attempting to implement it, I encountered an issue with the constructor lacking arguments. Despite my efforts to troubleshoot, I have been unab ...

Encountering the error "No overload matches this call" while utilizing useQuery in TypeScript may indicate a mismatch in function parameters

My issue lies with TypeScript and types. Here is the API I am working with: export const clientAPI ={ //... getOptions: async (myParam: number) => get<{ options: Options[]; courses: any[] }>(`/courses?myParam=${myParam}`)().then((result) =& ...

Guide on incorporating the authorization function from next-auth into a TypeScript Next.js 13 app directory

Can you help me understand the proper way to declare the authorize function in [...nextauth].ts? I have been attempting it as shown below: export default NextAuth({ session: { strategy: "jwt" }, providers: ...

The Docker image was successfully constructed, but unfortunately it is not located local when executing the coverage test in Azure pipeline

My objective is to create and execute coverage tests and then publish the results on Sonar. Below is the Dockerfile I am using: FROM node:12.22.12-buster-slim as base RUN apt update &&\ apt install --yes --no-install-recommends \ ...

What is the best way to design a circular icon using OpenLayers?

I am currently incorporating openlayers into my ionic app and working on placing users on the map. I have encountered a problem as I am unsure how to apply custom CSS styling to the user element, which is not directly present in the HTML. In the screenshot ...

How do I determine if a child component is in a dirty state within CanDeactivateGuard when dealing with multiple form tags?

Currently, I am utilizing a template driven form within my project. The parent component that I am working on is as follows: parent.component.html <tab> <form> <input></input> <button></button> </form ...

Problems encountered when utilizing $in operator in Mikro ORM MongoDB operations

For my project, I'm utilizing mikro orm with MongoDB to handle database operations in TypeScript. So far, it has proven to be the most effective ORM for MongoDB in this language. However, I've encountered type errors when using $in with Object ID ...

Having trouble retrieving information from Vuex store in Vue component when using TypeScript

I'm facing an issue with fetching data in my Vue component using Typescript. Upon logging in, I trigger an API call to retrieve data. Once the data is received, I store it using a Vuex module. @Action async getData(): Promise<TODO> { return ne ...

Enhancing AWS Amplify Auth elements using TypeScript

My goal is to enhance the existing Auth components within AWS Amplify like SignIn, SignUp, etc. by customizing the showComponent() function to display a personalized form. I found a helpful guide on how to achieve this at: While working on my nextjs proje ...

TestingCompilerFactory is not available as a provider

Currently troubleshooting my test file to identify the issue that is hindering a successful test run: import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { Component, Directive, Input, OnInit } from '@angula ...

Guide to accessing a nested and potentially optional object property with a default value and specifying its data type

Just a simple query here... my goal is to extract data.user.roles, but there's a possibility that data may be empty. In such cases, I want an empty array as the output. Additionally, I need to specify the type of user - which in this instance is any. ...

What is the best way to send an object to an Angular form?

I am facing an issue with my Spring entity, Agent, which includes an Agency object. When adding a new agent, I need to pass the agency as an object in the Angular form. While the backend code is functioning correctly, I am struggling to figure out how to p ...

Using Angular to transfer a function to a directive

Looking to pass the (scroll) method to a directive, I initially had it declared like this: <div class="table-responsive" pyb-fixed-table #container> After modifying it to include the method reference: <div class="table-responsive" (scroll)="onS ...

Dynamic cell editing feature in PrimeNG table

Looking to implement the PrimeNG Table. https://i.stack.imgur.com/bQycr.png Check out the live demo on StackBlitz. The table has three editable columns. The "Property Name" column always displays a text box in edit mode, while the "Property Value Type" ...