Angular 11 throws an error stating that the argument of type 'null' cannot be assigned to a parameter of type 'HttpClient'

As I embark on my journey to becoming a developer, I encounter a problem when passing a null argument as shown below:

todos.component.spec.ts

 
 import { TodosComponent } from './todos.component';
 import { TodoService } from './todo.service';
 import { Observable } from 'rxjs/Observable';
 import 'rxjs/add/observable/from';
    
    describe('TodosComponent', () => {
      let component: TodosComponent;
      let service: TodoService;
    
      beforeEach(() => {
        service = new TodoService(null); //Argument of type 'null' is not assignable to parameter of type 
      'HttpClient'.ts(2345)
        component = new TodosComponent(service);
      });
    
      it('6.1 Should set todos property with the items returned from the server', () => {
    
        const todos = [1, 2, 3];
        spyOn(service, 'getTodos').and.callFake(() => {
          return Observable.from([todos]);
        });
    
        component.ngOnInit();
    
        expect(component.todos).toBe(todos);
      });
    });

todo.component.ts


import { TodoService } from './todo.service'
    export class TodosComponent  { 
      todos: any;
      message: any; 
    
      constructor(private service: TodoService) {}
    
      ngOnInit() { 
        this.service.getTodos()
          .subscribe(t => this.todos = t);
      }
    
      add() { 
        var newTodo = { title: '... ' };
        this.service.add(newTodo)
          .subscribe(
          ( t => this.todos.push(t) ),
          ( err  => this.message = err) );
      }
    
      delete(id: number) {
        if (confirm('Are you sure?'))
          this.service.delete(id)
          .subscribe();
      }  
    }

todo.services.ts


import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/map';

    export class TodoService { 
      constructor(private http: HttpClient) { 
      }
    
      add(todo: { title: string; }) {
        return this.http.post('...', todo)
              .map((r => r.json()));
      }
    
      getTodos() { 
        return this.http.get('...')
              .map((r => r.json()));
      }
    
      delete(id: number) {
        return this.http.delete('...')
              .map((r => r.json()));
      }
    }

Here are the details of my current environment:

Angular CLI: 11.2.6
Node: 12.16.2
OS: win32 x64

Angular: 11.2.7
... animations, common, compiler, compiler-cli, core, elements
... language-service, platform-browser, platform-browser-dynamic
... router
Ivy Workspace: Yes

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1102.6
@angular-devkit/build-angular   0.1102.6
@angular-devkit/core            11.2.6
@angular-devkit/schematics      11.2.6
@angular/cdk                    11.2.6
@angular/cli                    11.2.6
@schematics/angular             11.2.6
@schematics/update              0.1102.6
ng-packagr                      11.2.4
rxjs                            6.6.6
typescript                      4.0.7

Answer №1

When working with the TodoService, it is important to inject the HttpClient because the service requires it as a parameter. To avoid making actual HTTP requests during testing (as we are focusing on testing the code itself and not the API), we can create a spy for the HttpClient and then pass it to the service.

import { of } from 'rxjs'

describe('TodosComponent', () => {
  beforeEach(() => {
    const spy = jasmine.createSpyObj('HttpClient', { post: of({}), get: of({}) })
    service = new TodoService(spy)
  })
})

Additional Note:

You can simplify the spy setup by using the following approach:

let todos = [1,2,3,4]
spyOn(service, 'getTodos').and.returnValue(of(todos));

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

Aligning an object in ThreeJS to always face the camera, ensuring it is perfectly straight and flat

Reviewing this demo http://codepen.io/anon/pen/JdmMPW, I am working on creating a camera orbiting around a sphere with text labels/satellites (represented by the plane object) that should always face the camera. function render() { marker.lookAt(camera.p ...

Filtering data in VueJs using Vuetify's v-tabs feature

I am currently utilizing NuxtJs, a lightweight version of the VueJS framework. My goal is to implement a data filtering functionality based on tab clicks. The objective is to display the data in alphabetical order and filter them accordingly when tabs are ...

What could be the reason for the onClick event functioning only once in HTML?

Below is the code snippet containing both HTML and JavaScript. However, the issue I am facing is that the onclick event only seems to work for the first <li>. <!DOCTYPE html> <html> <body> <ul class="list"> <li ...

The Ultimate Guide to Automatically Updating JSON File URLs

I am currently working on a project where I need to retrieve data from a URL using the $.getJSON method. I am interested in finding a way to continuously update this data and replace it in the HTML without needing to manually refresh the page. Although I h ...

Angular 8 feature module routing encompasses various components working together collaboratively

I am currently working on integrating a main module and a feature module that consists of various components. Below, I have provided the configuration for multiple routes within the feature routing file. const priorityRoutes: Routes = [ { path: &a ...

What is the best way to synchronize API definitions between the server and client using TypeScript?

My setup involves a server (TypeScript, NestJS) and a client (TypeScript, Angular) that communicate with each other. Right now, I have the API response DTO classes defined in both the server to output data and in the client to decode the responses into a ...

Using a Typescript variable prior to its assignment

I encountered an issue in my Typescript / ReactJS project displaying the error message Variable 'myVar' is used before being assigned. TS2454 This problem arises with my TS version 4.2.3, appearing both in my IDE and during code execution. Inte ...

Turn off the chrome react DevTools when deploying to production to ensure the

I have successfully browserified my react app for production using gulp and envify to set up NODE_ENV. This has allowed me to remove react warnings, error reporting in the console, and even disable some features like the require of react-addons-perf. Afte ...

what is the process for configuring a Universal link using javascript?

I have taken all the necessary steps to utilize a universal link. I created an AASA file, verified it using aasa-validator, and configured it in XCODE as required. Now, I am facing the challenge of setting up a hyperlink on my webpage that can redirect us ...

I encountered an issue while working with Material-UI and Mobx. The error message reads: "Material-UI: capitalize(string) function requires a string argument

enter code hereI encountered this issue when I copied a React component from and the state of this component is managed by Mobx as shown below: @observable snackbarState = { open: false, vertical: null, horizontal: null, }; @action toggle ...

How to Incorporate an Anchor Link into a Div as well as its Pseudo Element using CSS, Javascript, or jQuery

How can I make both the menu item and its icon clickable as a link? When either is clicked, the link should work. Here is a CodePen example: http://codepen.io/emilychews/pen/wJrqaR The red square serves as the container for the icon that will be used. ...

Performing asynchronous operations in React with axios using loops

On the backend, I have a socket set up to handle continuous requests from the server. Now, my goal is to send requests to the backend API continuously until a stop button is clicked. Using a loop for this task is considered bad practice as it never checks ...

Experiencing an issue with Jest - Error: unable to access property 'forEach' of null

After watching some tutorials, I decided to create a sample project in Jest for writing tests. In a TypeScript file, I included a basic calculation function like this: Calc.cs export class Calc { public add(num1: number, num2: number): number { ...

Leverage scope Variable in Angular Service URL

Currently, I am aiming to retrieve data from an API by sending specific search parameters through an AngularJS service. Within my ng-model, I have a variable named "search" that I want to utilize as a parameter in the API URL. My initial (unsuccessful) at ...

Exploring nested JSON objects in Angular and rendering them in PHP

On my Json page, I have data organized like this : [{ "qid": "1", "contester": "0", "answer": "0", "question": "What would you do after getting into ...

Tips for choosing multiple files with the Ctrl key in a list item element:

We have decided to create our own browsing functionality due to the limitations of the existing HTML browse feature. While using the HTML browse, we can only select multiple files by pressing the Ctrl key, and we want to replicate this feature in our custo ...

Checking for the Existence of a Database Table in HTML5 Local Storage

Upon each visit to my page, I automatically generate a few local database tables if they do not already exist. Subsequently, I retrieve records from the Actual Database and insert them into these newly created local tables. I am wondering if there is a me ...

Get started with the free plan for sails.js on Paas

Looking to test out my sails.js application deployment options. Can't seem to find sails.js on the supported list for Heroku and OpenShift's node.js offerings. Are there any free Platform as a Service (PaaS) plans available for sails.js? ...

Exploring the process of setting up a datasource for Select2 in October CMS using the integrated Ajax Framework

Looking to utilize the extensive AJAX framework provided by October CMS to populate a Select2 box with data. The process of using a remote dataset in Select2 involves the following steps: $(".js-data-example-ajax").select2({ ajax: { url: "https://a ...

Module '@foo' cannot be located within the ts-jest setup in a monorepository

My monorepo is set up with TypeScript, WebPack, and ts-jest. The build process is successful, but I'm running into issues with unit testing in the ./demo sub-project due to the error: Cannot find module '@mlhaufe/graphics/adapters' or its c ...