Issue: The inject() function can only be executed within an injection context. Issue: An untruthy value was expected to be truth

I'm currently in the process of setting up a unit test for my app.component. I've imported all the necessary components, but I keep encountering an error that's puzzling me. I activated "preserveSymlinks": true in my angular.json file, but the issue persists. How can I resolve this?

The error: Error: inject() must be called from an injection context

Here is a snippet of my ts file:

import { Component } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { LoginService } from 'is-common';
import { CookieService } from 'ngx-cookie';
import { Api } from 'is-common';

// More code follows...

This is how I set up my Test:

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA } from '@angular/core';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
import { Api } from 'is-common';
import { LoginService } from 'is-common';
import { HttpClientTestingModule } from '@angular/common/http/testing';

describe('AppComponent', () => {
    // Code for testing the component...

My tsconfig.app.json configuration looks like this:

{
  "extends": "./tsconfig.json",
  // More compiler options and configurations...
}

Answer №1

It seems like the issue may be originating from the Api, CookieService, or LoginService. One solution could be to mock these external dependencies.

You can try the following approach:

describe('AppComponent', () => {
    let component: AppComponent;
    let fixture: ComponentFixture<AppComponent>;
    // !! update these lines !!
    let mockApi: jasmine.SpyObj<Api>;
    let mockLoginService: jasmine.SpyObj<LoginService>;
    let mockCookieService: jasmine.SpyObj<CookieService>;

    beforeEach(() => {
        // Create a new spy before each test
        // The first string is an identifier for the mocked object
        // The array of strings are public methods
        // If unsure about the public methods of API, provide an empty object
        mockApi = {};
        mockLoginService = jasmine.createSpyObj<LoginService>('LoginService', ['isLogged', 'setApiURL', 'setDefaultClient']);
        mockCookieService = jasmine.createSpyObj<CookieService>('CookieService', ['get']);
        TestBed.configureTestingModule({
            imports: [
                HttpClientTestingModule,
                RouterTestingModule
            ],
            declarations: [
                AppComponent
            ],
            providers: [
                // !! Use the mocks for all external dependencies
                { provide: Api, useValue: mockApi },
                { provide: LoginService, useValue: mockLoginService },
                { provide: CookieService, useValue: mockCookieService }
            ],
            schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA]
        }).compileComponents();
    });

    beforeEach(() => {
        fixture = TestBed.createComponent(AppComponent);
        component = fixture.componentInstance;
    });

    it('should create the app', () => {
        expect(component).toBeTruthy();
    });
});

The above adjustments should help resolve the issue. Mocking external dependencies is a good practice in testing.

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

Does this fall under the category of accepted practices for employing an effect in Angular?

I am working on integrating an Angular directive with a signal that receives values from a store selector. This signal is crucial for determining whether a button should be disabled or not. I'm curious about the best approach to listen to this signal ...

React Redux Bundle with Hot Reload Feature

Working on a project written in TypeScript with the React and Redux framework, I'm familiar with webpack and its middleware libraries for hot reloading. My question arises when considering how my TypeScript code is first converted to JSX through gulp ...

Creating a table and filling it with data from any cell is a simple process

I have a question about creating an HTML table similar to the image shown here: image I want to populate the table with data from a JSON response received from a web service: { "ErrorCode": 0, "ErrorMessage": "ok", "Data": [ { ...

Error in Firebase Emulator: The refFromUrl() function requires a complete and valid URL to run properly

Could it be that refFromURL() is not functioning properly when used locally? function deleteImage(imageUrl: string) { let urlRef = firebase.storage().refFromURL(imageUrl) return urlRef.delete().catch((error) => console.error(error)) } Upon ...

Changing the mouse cursor dynamically with Angular programming

What is the recommended approach for changing the mouse cursor programmatically in Angular? For instance: HTML: <div [style.cursor]="cursorStyle">Content goes here</div> or <div [ngStyle]="{ 'cursor': cursorStyle ...

Steps to retrieve a date from a form control

html <form [formGroup]="searchForm" (ngSubmit)="search()"> <div class="row"> <div class="col"> <input type="date" class="form-control" formControlName="startD ...

SVG: organizing objects based on event priority

I am struggling with layering and event handling in an SVG element. Check out the example here: https://stackblitz.com/edit/angular-ivy-rkxuic?file=src/app/app.component.ts app.component.ts import { Component, VERSION } from '@angular/core'; @ ...

An easy way to insert a horizontal line between your text

Currently, I have two text responses from my backend and I'm considering how to format them as shown in the design below. Is it possible to automatically add a horizontal line to separate the texts if there are two or more broadcasts instead of displa ...

When receiveMessage is triggered, the FCM push notification fails to refresh the view

After following this helpful tutorial on Push Notifications with Angular 6 + Firebase Cloud Messaging, everything is working perfectly. I am able to receive notifications when using another browser. To ensure that my notification list and the length of no ...

Error message: Angular 2's NgFor directive can only bind to iterable data types like Arrays

One of the challenges I'm facing involves working with a specific model: export class CoreGoalModel { constructor( public title: string, public image: string, ){} } In order to retrieve data based on this model, I've set up a s ...

Is it possible to modify the HTML/CSS of a child component using the parent component in Angular 2+?

Is there a way to dynamically add text and style to a specific row in a child component based on the parent's logic? (parent): <body> <child-component></child-component> </body> (child): <div *ngfor = "let record in r ...

The TypeScript compiler is unable to locate the identifier 'Symbol' during compilation

Upon attempting to compile a ts file, I encountered the following error: node_modules/@types/node/util.d.ts(121,88): error TS2304: Cannot find name 'Symbol'. After some research, I found that this issue could be related to incorrect target or l ...

Identifying modifications within the @Input property in Angular 4

Can someone clarify how to detect changes in an @Input property within a component, rather than just when passed from its parent? I haven't found a clear answer to this yet. Thank you! ...

`Incorporating CSS Pseudo-elements to Customize Angular Font Awesome Icons Issue`

I successfully integrated @fortawesome/angular-fontawesome into my Angular 7 application by following the instructions provided on https://www.npmjs.com/package/@fortawesome/angular-fontawesome. Although I am able to use the icons directly, I am facing di ...

Nested ControlGroup in Angular2's ControlArray

I've hit a roadblock trying to iterate through a ControlArray that has Controlgroups in a template. In TypeScript, I successfully created the ControlArray and added some ControlGroups by looping over data fetched from an API. The console displays the ...

Implementing Basic Authentication for HTTP Requests in Angular 7

Currently, I am working with angular 7 along with Spring Boot and Spring Security. Within the Back End, I have successfully implemented basic authentication. However, while attempting to send a request from Angular with an Http Header that includes User n ...

Tips for extracting images from an ion-img element when the source is a PHP script that generates a captcha code

For my college project, I am scraping a website to display the results. One issue I'm facing is that the results are protected by a captcha code. I attempted to scrape using a node HTML parser, but when I extracted the src attribute, it pointed to c ...

Error TS2322: Type 'boolean' cannot be assigned to type 'undefined'. What is the best approach for dynamically assigning optional properties?

I am currently working on defining an interface named ParsedArguments to assign properties to an object, and here is what it looks like: import {Rules} from "../Rules/types/Rules"; export interface ParsedArguments { //other props //... ...

attempting to refine an array of objects using another array within it

I am currently filtering a group of objects in the following manner: [ { "Username":"00d9a7f4-0f0b-448b-91fc-fa5aef314d06", "Attributes":[ { "Name":"custom:organization", "Valu ...

Ways to incorporate Bootstrap components into an Angular application without relying on external modules

I'm attempting to activate Bootstrap 5.3 Tooltips within my Angular 17 application. Within angular.json, I've added bootstrap.bundle.min.js, which includes PopperJS. "scripts": [ "node_modules/bootstrap/dist/js/bootstrap.bundle. ...