The issue lies in attempting to assign an 'Observable<number[]>' to a parameter expecting an 'Observable<ProjectObject[]>'. This obstacle must be overcome in order to successfully create a mock service

I am currently working on setting up a mock service for unit testing, but I am facing an issue where the observable is not returning the expected fake value. Can someone please assist me in resolving this problem and also explain what might be wrong with my code?

all-projects.component.spec.ts

import { ProjectsService } from './../../../../services/projects/projects.service';
import { AllProjectsComponent } from './all-projects.component';

import 'rxjs/add/observable/from';
import { Observable } from 'rxjs/Observable';


describe('allprojectComponent', () => {

    let component: AllProjectsComponent;
    let service: ProjectsService;

    beforeEach(() => {
        service = new ProjectsService(null, null);
        component = new AllProjectsComponent(service);
    });

    it('should set projects property with the items returned from the server', () => {
        spyOn(service,'getAllprojects').and.returnValue(Observable.from([[1,2,4]]))
    })
});

This section corresponds to my service file.

project.service.ts

import { Injectable } from '@angular/core';
import { HttpClient , HttpBackend, HttpParams  } from '@angular/common/http';
import { environment } from './../../../../environments/environment';

import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ProjectsService {
  public API = environment.apiUrl;
  public newHttp;

  constructor( private http: HttpClient, private handler: HttpBackend ) {

    this.newHttp = new HttpClient(this.handler);

  }

  getAllprojects(): Observable<ProjectObject[]> {
    return this.http.get<ProjectObject[]>(this.API + '/projects');
  }

The following snippet defines my project model. project.model.ts

export interface Docs {
    fileType : string,
    extension: string
}



export interface Project {
    projectType: string;
    status: string;
    totalBids: number;
    _id: string;
    clientID: string;
    projectName: string;
    licenseType: string;
    location: string;
    description: string;
    duration: number;
    createdAt: Date;
    updatedAt: Date;
    __v: number;
}

export interface OpenFaq {
    _id: string;
    engineerID: string;
    question: string;
}

export interface ProjectObject {
    project: Project;
    openFaq: OpenFaq[];
    closedFaq: any[];
    doc: any[];
}

Answer №1

Below is a simple example of how to set up a test:

  it('should populate projects property with items from the server', () => {
    spyOn(service, 'getAllprojects').and.returnValue(of([
      // You can provide the full properties of ProjectObject or just what's needed for the test to pass
      {} as ProjectObject,
      {} as ProjectObject,
      {} as ProjectObject,
    ]));

    component.methodName(); // calling method that subscribes to the service

    // Add your assertions related to fetching data from the service
  });

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

Concealing tab bars on Ionic 2 secondary pages

In my Ionic Bootstrap configuration, I have the following setup: { mode: 'md', tabsHideOnSubPages: true } However, despite having this setting in place, the tabs still appear on some sub-pages. It seems to be happening randomly. Is there ...

Determine the output type of a function in Typescript using an input value specified by an enum

I am currently saving settings to local storage and want to be able to input responses when retrieving (and possibly inserting) values from/to the storage. After researching, it seems that using function overloading is the best approach. Here is what I ha ...

A more concise validation function for mandatory fields

When working on an HTML application with TypeScript, I encountered a situation where I needed to build an error message for a form that had several required fields. In my TypeScript file, I created a function called hasErrors() which checks each field and ...

Filter a two-dimensional array based on the presence of a string value found in the second array

My logic for this assignment is not very good, as I need to filter a 2D array based on the values of another array. Let me provide an example of the 2-Dimensional Array: const roles = [ ['roles', 'admin', 'write'], ['ro ...

The specified type 'x' cannot be assigned to the type 'x'. Error code: 2322

I encountered an issue with the code in @/components/ui/billboard.tsx file import { Billboard } from "@/types" interface BillboardProps { data: Billboard; }; const BillboardComponent: React.FC<BillboardProps> = ({ data }) => ...

Dealing with Angular State Management Across Components (Direct Dependency): encountering a NullInjectorError - R3InjectorError

I have encountered a NullInjectorError in my Angular application and I am seeking assistance in resolving it. To provide context, my application consists of three main components: ProductRegistrationAndListingScreen, ProductList, and ProductRegistration. ...

Which option is more beneficial for intercepting API data in Angular 6: interfaces or classes?

My API returns JSON data that is not structured the way I need it, so I have to make changes. { "@odata.context":"xxxxxx", "id":"xxxxxxxx", "businessPhones":[ ], "displayName":"name", "givenName":"pseudo", "jobTitle":null, "ma ...

Embedding a module within a fluid element

Creating a dynamic component and projecting template inside it can be done easily with the following code snippet - @Component({ selector: 'dynamic', template: ` <p>Dynamic Component</p> <ng-content></ ...

Is there a way to extract a specific item from a ListView by tapping on it in Nativescript?

Attempting to retrieve data from a tap event using angular2 + typescript: This is the html code for the component: <RadListView row="1" [items]="groceryList" [class.visible]="listLoaded" (tap)="seeItem($event)" swipeActions="true" (itemSwipeProgr ...

Angular 2 Date Input failing to bind to date input value

Having an issue with setting up a form as the Date input in my HTML is not binding to the object's date value, even though I am using [(ngModel)] Here is the HTML code snippet: <input type='date' #myDate [(ngModel)]='demoUser.date& ...

Testing React components with the React Testing Library and Material UI version 4, exploring hidden components

Exploring react testing library for the first time. I encountered an issue while attempting to test my code that is wrapped with the Hidden Component from material UI. Surprisingly, despite the component being visible in the DOM, the test fails. Snippet o ...

Angular 2 User Interface with Drag-and-Drop Functionality

I have been searching for a solution that would allow me to drag HTML elements and place them anywhere on the screen. After exploring different options, I came across 2 packages: https://github.com/valor-software/ng2-dragula https://github.com/akser ...

How to Dynamically Enable or Disable a Button in Angular 2 Based on Text Field Values

I am facing a situation where my UI contains multiple text boxes and dropdown fields. My goal is to activate a button on the UI as soon as one of these fields has a value. I have set up a function that is triggered by the ngModel values assigned to these f ...

Angular 2: A guide to resetting dropdown and text values when changing radio button selections

When the user interface displays two radio buttons - one for YES and one for NO - and the user clicks on YES, a dropdown is shown. Conversely, if the user clicks on NO, a textbox is displayed. How can I clear the values in the dropdown and textbox when s ...

Provide a string argument when instantiating an abstract class

I am searching for a method to assign a name string within a class and utilize it in the abstract class at the constructor level, without the need for a function. Opening up the constructor is not an option due to using typedi. You can access the playgrou ...

The "ngx-phone-select" directive is not defined with the "exportAs" attribute

Having an issue with ngx-phone-select in the phone number field, receiving the error message "There is no directive with "exportAs" set to "ngx-phone-select" http://prntscr.com/hzbhfo This problem occurs in Angular 4.3 using ngx-phone-select version 1.0. ...

Reacting to the dynamic removal of spaces

Is there a way to dynamically remove the space between removed chips and older chips in Material-UI when deleting one of them? <div className="row contactsContainer"> {contacts.map((contac ...

Having Trouble with React, TypeScript, and MUI Tabs? Dealing with Overload Errors?

Currently, I'm in the process of building a component using MUI Tabs. Here's a snippet of my code: <Box> <Tabs value={value} onChange={handleChange} variant='fullWidth'> {RoomTabs.map((tab, index) => ( ...

Challenges encountered when using promises for handling mysql query results

I've been working on creating a function that will return the value of a mysql query using promises. Here's what I have so far: query(query: string): string { var response = "No response..."; var sendRequest = (query:string): Prom ...

Exploring methods to verify a service subscription to a topic provided by a different service

My services provide the following functionalities: @Injectable({ providedIn: 'root' }) export class Service1 { dataHasChanged = new Subject(); private data1; private data2; constructor() {} getData() { return { data1: th ...