I am encountering an issue with my code where the function this.ProductDataService.getAllProducts is not recognized when

Encountering an issue while running unit test cases with jasmine-karma in Angular 7. The error received is:

ProjectManagementComponent should use the ProjectList from the service

TypeError: this.ProjectManagementService.getProject is not a function

If I switch from useValue to useClass, another error occurs:

[object ErrorEvent] thrown

Despite trying various options, I am unable to find a solution online.

app.component.spec.ts

describe('ProjectManagementComponent', () => {
  let comp: ProjectManagementComponent;
  let fixture: ComponentFixture<ProjectManagementComponent>;
  let de: DebugElement;
  let el: HTMLElement;

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ProjectManagementComponent],
      imports: [HttpClientModule, RouterTestingModule, RouterModule, NgbModule, NgxPaginationModule, FormsModule, ReactiveFormsModule, BrowserModule,],
      providers: [{ provide: ProjectManagementService, useClass: ProjectManagementService },
               {provide: ProductsService, useClass: ProductsService}]
    })
      .compileComponents().then(() => {
        fixture = TestBed.createComponent(ProjectManagementComponent);
        comp = fixture.componentInstance;
       de = fixture.debugElement.query(By.css('form[id=addProjectCreationData]'))
        el =de.nativeElement;
      });
  }));


it("should use the ProjectList from the service", () => {
    console.log("Create a Project Service")
    const projectService = fixture.debugElement.injector.get(ProjectManagementService);
    fixture.detectChanges();
    expect(projectService.getProject()).toEqual(comp.getResponse);
  });
});

app.component.service.stub.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { config } from "config";
const baseUrl: string = config.url;


@Injectable()
export class ProjectManagementServiceStub {
    constructor(private http: HttpClient) { }
              
    getProject(url) :Observable<any>{
        
        return this.http.get(url )
            .pipe(map(Response => Response))
                
    }

}

Answer №1

Revise your providers section to include the use of stub ( ProjectManagementServiceStub ) that you have created

 providers: [{ provide: ProjectManagementService, useClass: ProjectManagementServiceStub },
             {provide: ProductsService, useClass: ProductsService}] // <--- Ensure "stub" is injected here as well

On a side note: The it block below does not seem to make sense.

it("should use the ProjectList from the service", () => {
    console.log("Create a Project Service")
    const projectService = fixture.debugElement.injector.get(ProjectManagementService);
    fixture.detectChanges();
    expect(projectService.getProject()).toEqual(comp.getResponse);
  });
});

This overlooks the core principle of unit testing as you are testing projectService.getProject() which belongs to the service, not this component

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

Is it possible to replicate a type in TypeScript using echo?

Is there any equivalent in TypeScript to the following code snippet? type TypeA = { x: number }; printType(TypeA); I have found a method that consistently enables TypeScript to provide a type description. const y = { x: 1, z: 'hello', }; ...

A different approach to showcasing components in SvelteKit based on the width of the screen

In my SvelteKit app, I'm using this code to retrieve the current window size and switch the displayed component when the width is small: <script> let size; </script> <svelte:window bind:innerwidth{size}/> <div> {#if size &g ...

When transitioning from component to page, the HTTP request fails to execute

I have created a dashboard with a component called userInfo on the homepage. This component maps through all users and displays their information. Each user has a display button next to them, which leads to the userDisplay page where the selected user&apos ...

Determining the quantity of variations within a union in Typescript

Is it possible to determine the number of types in a union type in Typescript, prior to runtime? Consider the following scenario: type unionOfThree = 'a' | 'b' | 'c'; const numberOfTypes = NumberOfTypes<unionOfThree>; c ...

Show current time or clock using Angular framework

I have been utilizing the following method to showcase time in my application? constructor(private datePipe: DatePipe) {} ngOnInit() { this.getTime(); this.date = this.datePipe.transform(new Date(), "dd/MM/yyyy"); } getTime() { setInterval( ...

Routing with nested modules in Angular 2 can be achieved by using the same

Encountering a common issue within a backend application. Various resources can be accessed through the following routes: reports/view/:id campains/view/:id suts/view/:id certifications/view/:id Note that all routes end with the same part: /view/:id. ...

Tips for implementing lazy loading of modals in Angular 7's module structure

In a previous project, our team utilized a single "app module" that imported all necessary components, pipes, directives, and pages at the beginning of the application. However, this structure was not ideal as the app became slower with its growth. Upon t ...

The value of type 'number' cannot be assigned to type 'string | undefined'

Having an issue with the src attribute. I am trying to display an image on my website using the id number from an API, but when I attempt to do so, it gives me an error in the terminal saying 'Type 'number' is not assignable to type 'st ...

Establishing default parameters for angular pipes

Is there a way to establish default settings for an angular pipe without creating a custom one myself? I frequently utilize the currency pipe in this manner {{ price | currency:'EUR':'symbol':'0.2-2':'de' }} I&apo ...

How to remove the footer on a particular webpage

I am currently using angular version 14. On a specific page, there is a footer visible that I wish to hide. This page pertains to job search, and I would like to remove or conceal the footer specifically from this job search page. The footer has been separ ...

Innovative Functions of HTML5 LocalStorage for JavaScript and TypeScript Operations

Step-by-Step Guide: Determine if your browser supports the use of localStorage Check if localStorage has any stored items Find out how much space is available in your localStorage Get the maximum storage capacity of localStorage View the amount of space ...

Exploration of mapping in Angular using the HttpClient's post

After much consideration, I decided to update some outdated Angular Http code to use HttpClient. The app used to rely on Promise-based code, which has now been mostly removed. Here's a snippet of my old Promise function: public getUser(profileId: nu ...

The request to http://localhost:8000/api could not be completed due to a connection refusal error (

In the process of creating an Angular project aimed at displaying, adding, deleting, and updating employee details, I encountered persistent errors. Despite having my own API established with connections to Angular, Express, Node, and MongoDB, I continue f ...

Clicking the button will trigger the onclick event

I'm working on a button component in TypeScript and I have encountered an issue with passing the event to the submitButton function. import * as React from 'react'; interface Props { className?: string; text: string; onClick?(event: Reac ...

Ways to ensure that when changes occur in one component, another component is also updated

How can I update the cart badge value in the navbar component every time a user clicks the "Add to Cart" button in the product-list component? The navbar component contains a cart button with a badge displaying the number of products added to the cart. n ...

At what juncture is the TypeScript compiler commonly used to generate JavaScript code?

Is typescript primarily used as a pre-code deployment tool or run-time tool in its typical applications? If it's a run-time tool, is the compiling done on the client side (which seems unlikely because of the need to send down the compiler) or on the s ...

Error message occurs during compilation of basic Vue file in Webpack

When I execute webpack watch in the VS2017 task runner, it displays the following error: ERROR in ./wwwroot/js/src/App.vue Module build failed: SyntaxError: Unexpected token { at exports.runInThisContext (vm.js:53:16) at Module._compile (module.js:373:25) ...

Issue with iPad Pro displaying Bootstrap 4 Navbar toggle icon

Having trouble with my Bootstrap 4.1.1 navbar on iPadPro. It's not displaying the correct data from the div and it's not collapsing properly. However, it works fine on small devices. Any suggestions on how to fix this issue? Here's the code ...

"An error occurred stating that _co.JSON is not defined in

During my attempt to convert an object into a string using the JSON method, I encountered an error upon loading my page: Error: _co.JSON is undefined The stacktrace for this error message is extensive and seems unnecessary to include at this point. Th ...

Is it possible to use TypeScript in a React Native project with a JavaScript file?

Currently, I am learning React Native by working on app clones like Instagram and YouTube. I have recently started an AirBnb clone project, but I'm facing some issues with the initial build. One issue I noticed is that in 'App.js', the temp ...