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

The type 'myInterface' cannot be assigned to the type 'NgIterable<any> | null | undefined' in Angular

I am facing an issue that is causing confusion for me. I have a JSON data and I created an interface for it, but when I try to iterate through it, I encounter an error in my HTML. The structure of the JSON file seems quite complex to me. Thank you for yo ...

Issues encountered when retrieving data with ReactiveForms

My current project involves gathering data using ReactiveForms. Here is the structure of my setup: Initially, I create a modal to gather the necessary data: async present(){ const modal = await this.modalController.create({ component: dataComponent, cs ...

Event typeORM on afterUpdate in NestJS

After every update of my data in the log table, I want to insert an entry into another table. To achieve this, I have created an EntitySubscriberInterface. The event is triggering correctly, but the entity array does not include the updated id. async afte ...

Vertical and horizontal tabs not functioning properly in Mat tabs

I successfully created a vertical material tab with the code below, but now I am looking to incorporate a horizontal tab inside the vertical tab. Attempting to do so using the code provided results in both tabs being displayed vertically. Below is my code ...

Receive a notification when the div element stops scrolling

I am attempting to replicate Android's expandable toolbar within an Angular component. My HTML code appears as follows: <div (scroll)="someScroll($event)"> <div class="toolbar"></div> <div class="body"></div> </d ...

When using multiple select tags with *ngFor in Angular, modifying the value of the first select tag will have an

<table id="DataTable" border="1" ALIGN="center"> <tr ALIGN="center"> <th>name</th> <th>address</th> <th>number</th> <th>type</th> </tr> <tr class="tcat" *ngFor ...

Sharing code between Angular 8 and NodeJS 12: Best practices

Can code be shared between Angular 8 (TypeScript) and NodeJS 12? All the code is located on the same server but in separate directories /client and /server. A major issue we are facing is the duplication of regular expressions and constants across both A ...

Endure the class attribute in Angular 5

My SearchComponent has a route (/search) and SearchDetailComponent has a route (/search-detail:id). In the SearchComponent, there is a searchbox (input field) where I can type any text to start a search. After loading the search results and navigating to ...

Issue: In an Angular electron app, a ReferenceError is thrown indicating that 'cv' is

I have been working on a face detection app using OpenCv.js within an Angular electron application. To implement this, I decided to utilize the ng-open-cv module from npm modules. However, when attempting to inject the NgOpenCVService into the constructor ...

What methods can I use to make sure the right side of my React form is properly aligned for a polished appearance?

Trying to create a React component with multiple input field tables, the challenge is aligning the right side of the table correctly. The issue lies in inconsistent alignment of content within the cells leading to disruption in overall layout. Experimente ...

What is the purpose of importing the HttpClientModule in app.module.ts when it has already been imported in a different module specifically for its use?

Currently, I am working with 2 modules named AppModule and BookModule. In BookModule, a component is injected with a service that utilizes HttpClient, so I had to import HttpClientModule in it. However, the application still requires importing HttpClientMo ...

What is the best way to inform TypeScript that the output of the subscribe method should be recognized as an array containing elements of type

I'm facing a challenge understanding types while working with noImplicitAny and typescript in Angular 6. The compiler is indicating that the type of result is Object, even though I am certain it should be an array of type Manufacturer. Unable to assig ...

Can the arrow function properly subscribe to an Observable in Angular and what is the accurate way to interpret it?

I'm currently working through the official Angular tutorial: https://angular.io/tutorial/toh-pt4 Within this tutorial, there is a component class that subscribes to a service: import { Component, OnInit } from '@angular/core'; import { He ...

Revitalizing ngFor in Angular 9: Refreshing object properties for re-rendering

I am currently working with an array of objects named Guests: [ {id: 1, first_name: "Tom", last_name: "", logo: 2}, {id: 2, first_name: "John", last_name: "", logo: 3}, {id: 3, first_name: "Jim", l ...

What is the best way to vertically align items within a <div> using CSS in a React application?

The layout of the page looks like this: I am trying to center the Redbox (containing '1') within the "PlayerOneDiv". Similarly, I want to center the yellow box within "PlayerTwoDiv". return (<div className="App" ...

Utilizing "regression-js" within an Angular 2 project: A comprehensive guide

I have integrated the Regression npm module https://www.npmjs.com/package/regression into my Angular 2 application to utilize the Linear Regression functionality. I installed the package using "npm install regression". However, I encountered errors while a ...

Having trouble extracting a list of matches using a Regular Expression?

const stringWithDate: string = "4/7/20 This is a date!"; const reg: RegExp = new RegExp("^(\d{1,2}\/\d{1,2}\/\d{1,2})").compile(); const exist: boolean = reg.test(stringWithDate) const matches: RegExpExecArray | null = reg.exec(str ...

Angular Checkbox Click EventLearn how to handle click events on

How can I toggle the visibility of a form using ngIf when a click event is triggered by a checkbox? Below is the code for my column header and column values: <th><label class="btn btn-filter"> <input type="checkbox" ...

Are Handlebars and Angular 2 compatible?

Since the syntax for Angular expressions and Handlebars expressions is the same ({{ }}), I'm curious if we can utilize both at the same time. ...

Issue with react router v6: Component fails to render even though route has been changed

The router seems to be experiencing an issue where it does not render a component. Specifically, on the home page, the Private Route is only rendered once. Clicking on a NavLink changes the URL to "/agreements", but the component itself is not being render ...