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

https://i.sstatic.net/tjH6H.jpg

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

Typescript Error: Issue encountered while passing props. Unable to access properties as they are undefined

I encountered an issue where I created an object of a certain type and attempted to pass it to a component. However, when passing the props, I received an error message stating that it cannot read properties of undefined ('stepOne'). The error sp ...

Issues encountered when setting up a Context Provider in React using TypeScript

I am currently in the process of setting up a Cart context in my React TypeScript project, inspired by the implementation found here: https://github.com/AlexSegen/react-shopping-cart/blob/master/src/contexts/CartContext.js. I'm encountering some conf ...

Mock valid HTTP requests to URLs in Django for testing purposes

I am faced with a challenge in my urls.py file where multiple URLs are decorated with the login_required decorator. # Index Page url(r'^$', login_required(views.IndexPage.as_view()), name='index'), # Schedule urls url(r'^schedule ...

Step-by-step guide on building a mat-table with nested attributes as individual rows

Here is the data structure I am working with: const families = [ { name: "Alice", children: [ { name: "Sophia" }, { name: "Liam" ...

"Encountering issues with testing the controller of an Angular

I am facing difficulties while attempting to test a modal controller (developed using Angular UI Bootstrap). I simplified the test code as much as possible, but I keep encountering an error. Below is part of the modal controller: var controllersModule = ...

Is the ng-selector in Angular2 not sorting items alphabetically as expected?

This code snippet demonstrates the use of ng-selector in an .html file <ng-selector name="company" [(ngModel)]="company_selected" [formControl]="loanApplyForm.controls['company']" ...

Creating a channel for communication between sibling components in Angular 4 by storing component references in a shared service

I am searching for a way to establish communication between two sibling Angular 4 components. After reviewing the documentation at https://angular.io/guide/component-interaction, my idea revolves around utilizing a service that stores a reference to the c ...

Using ngrx store select subscribe exclusively for designated actions

Is it possible to filter a store.select subscription by actions, similar to how we do with Effects? Here is an example of the code in question: this.store .select(mySelector) .subscribe(obj => { //FILTER SUBSCRIPTION BY ACTION this.object = ob ...

Handling network connection errors in Ionic 2

Handling API calls in my provider involves the following method: listSavedJobs() : Promise <any> { let headers = new Headers({ 'Authorization': localStorage.getItem('token') }); return this.http.get(this.savedJobs, { h ...

How can a singleton object be referenced or injected into a constant in Angular?

I have experience implementing dependency injection in a component class. For example: constructor(private staticDataService: StaticDataService) But I am curious if it's possible in Angular 7 to inject the singleton staticDataService object as an at ...

Showing the state on a different page: A step-by-step guide

I'm currently in the process of creating a model for a real estate website. On the homepage, users can choose between 'rent' or 'purchase' using a select option and view the results on that page. I have successfully stored the sear ...

Ways to achieve outcomes from functions employing concatMap within rxjs?

When calling two functions, I make use of fn1 and fn2. To execute them one after the other, I utilize concatMap. I choose not to use exhaustMap and switchMap as they can result in nested "callback-hell". exhaustMap(() => fn1().pipe( swit ...

Unlock specific elements within the "sub-category" of a combined collection

If my union type is structured like this: type StateUpdate = { key: 'surname', value: string } | { key : 'age', value: number }; This setup is convenient because it allows me to determine the type of the value based on the key. Howev ...

What could be causing MongoDB to not delete documents on a 30-second cycle?

Having trouble implementing TTL with Typegoose for MongoDB. I am trying to remove a document from the collection if it exceeds 30 seconds old. @ObjectType("TokenResetPasswordType") @InputType("TokenResetPasswordInput") @index( { cr ...

Error encountered while building with Next.js using TypeScript: SyntaxError - Unexpected token 'export' in data export

For access to the code, click here => https://codesandbox.io/s/sweet-mcclintock-dhczx?file=/pages/index.js The initial issue arises when attempting to use @iconify-icons/cryptocurrency with next.js and typescript (specifically in typescript). SyntaxErr ...

Angular 2 template format standard

Every Angular 2 example I encounter seems to place the template within the component decorator. import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: '<h1>Hello world</h1>' }) e ...

The absence of a 'defaultValue' argument in Typescript React is causing an issue

I'm encountering an issue with my code. The error message states "An argument for 'defaultValue' was not provided." I am trying to set default values but unsure of what those values should be. Additionally, I am facing a couple of other err ...

Use the rowTemplate in a Kendo grid without replacing the existing one

I am currently utilizing Angular 1.4 with TypeScript and Kendo UI (employing angular directives). My goal is to create a RowTemplate for each row that dynamically changes the color based on a specific property of the item. While I am aware of jQuery solu ...

I implemented progress bars in Angular 2 that have changing maximum values. The service updates the maximum value for each bar dynamically. Currently, the progress bars are functioning at 100% capacity

this.games=[ {"val":50, "name":"Articlescontributed","max":35}, {"val":30 ,"name":"Articlesrated", "max":999}, {"val":20, "name":"Views", "max":35}, {"val":30, "name":"Ratings", "max":35}, {"val":20, "name":"Follower", "max":200}, { ...

Guide on streamlining interface initialization within a React project using Typescript

Working on my Typescript project, I consistently utilize an interface within the State of various components: interface Item { selectedValue: string originalSelectedValue: string loading: boolean disabled: boolean isValid?: boolean } ...