Testbed: Issue encountered: Unable to resolve all parameters for PriDateInput component

I am facing an issue while creating an Angular Component with the help of TestBed. The error message I receive is as follows:

Error: Can't resolve all parameters for PriDateInput: (?). error properties: Object({ ngSyntaxError: true })

The component named PriDateInput contains a service called AppContextService that needs to be injected. My intention is to mock the AppContextService by substituting it with MockAppContextService.

Below is the content from the .spec file:

class MockWindowService extends WindowService {
        get href() : string {
            return "https://elevationfw-iridium-build.azurewebsites.net/Default/Azure-DEV/#/";
        }
    } 

    class MockAppContextService extends AppContextService {
        constructor(){
            super(new StorageService(), new MockWindowService());
        }
        getContext() {
            let emptyContext: any = this.emptyContext;
            emptyContext.user.culture = "en-US";
            return this.emptyContext;
        }
    } 

    describe('AppContextService Test cases', () => {
        let mockApp = new MockAppContextService();
        let priDateInput: PriDateInput;
        debugger;
        beforeEach(() => {
            TestBed.configureTestingModule({
                declarations: [PriDateInput],
                providers: [
                    {
                        provide: AppContextService,
                        useClass: mockApp
                    }
                ],
            });
            priDateInput = TestBed.get(PriDateInput);
        });

        it('should be possible to instantiate it', () => {
            expect(priDateInput).toBeDefined();
            expect(priDateInput).not.toBeNull();
        });

        it('should be possible to instantiate it', () => {

            expect(priDateInput).toBeDefined();
            expect(priDateInput).not.toBeNull();
        });
    });
    

Here is an excerpt of my component:

import { Component, OnInit, OnDestroy, ViewChild, ElementRef, Input, Output, EventEmitter } from "@angular/core";
    import { AppContextService } from "./../../../../../services/appcontext.service";
    import * as moment from 'moment';
    
    @Component({
        selector: "pri-date-input",
        templateUrl: './input.date.component.html'
    })
    
    export class PriDateInput implements OnInit, OnDestroy {
        .............................
        @ViewChild("input") input: ElementRef;
    
        @Input("domainType") domainType: String;
        @Input("required") required: Boolean;
        @Input("isLoading") isLoading: boolean;
        @Input("isDisabled") isDisabled: boolean;
        @Input("onWriteValue") onWriteValue: EventEmitter<string | null>;
        @Output("onDateChange") onDateChange: EventEmitter<string> = new EventEmitter<string>();
    
        constructor(
            private _appContextService: AppContextService
        ) {
            moment.locale(this._appContextService.user.culture);
        }
    
        ngOnInit(): void {
            .......
        }
    
        ngOnDestroy(): void {
            this.unsubscribeInputEvents();
        }
        ......
    }
    

If you require additional information, please feel free to ask :)

Answer №1

When creating a new instance of a class, you can use it as a mock like this:

let mockApp = new MockAppContextService();

Instead of using `useClass`, try using `useValue` when providing the service:

{
  provide: AppContextService,
  useValue: mockApp
}

Don't forget to include these additional steps in your testing code:

TestBed.configureTestingModule(/* configuration */)
  .compileComponents();

fixture = TestBed.createComponent(PriDateInput);
component = fixture.componentInstance;
fixture.detectChanges();

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

Having trouble retrieving information from a JSON object? Unable to retrieve property 'company_about' of an undefined object?

Here is the JSON data I have: [ { "id": 1, "job_id": 1, "company_profile": "Sales and Marketing", "company_about": "Established in 1992 , it is a renouned marketing company", "company_product": "Ford,Mustang,Beetle", "key_skills": ...

After refreshing, the LocalStorage in Angular 2 seems to disappear

Something a little different here :) So, when attempting to log a user in, I am trying to store the access_token and expires in localStorage. It seems to be working "okay". However, if I refresh the page, the tokens disappear. Also, after clicking the log ...

Guide to separating the bytes of a number and placing them into an Uint8Array

I am looking to convert a JavaScript number into the smallest possible uint8array representation. For example : 65 535 = Uint8Array<[255,255]> (0b1111111111111111 = [0b11111111, 0b11111111]) 12 356 = Uint8Array<[48,68]> (0b0011000001000100 = [ ...

Triggering event within the componentDidUpdate lifecycle method

Here is the code snippet that I am working with: handleValidate = (value: string, e: React.ChangeEvent<HTMLTextAreaElement>) => { const { onValueChange } = this.props; const errorMessage = this.validateJsonSchema(value); if (errorMessage == null ...

Prisma: Utilizing the include option will retrieve exclusively the subobject fields

I created a function to filter the table building and optionally pass a Prisma.BuildingInclude object to return subobjects. async describeEntity(filter: Filter, include?: Prisma.BuildingInclude): Promise<CCResponse> { try { const entity = await ...

Tips for passing TouchableOpacity props to parent component in React Native

I created a child component with a TouchableOpacity element, and I am trying to pass props like disabled to the parent component. Child component code: import React from 'react'; import {TouchableOpacity, TouchableOpacityProps} from 'react- ...

What are the steps for integrating and expanding a JavaScript library using rollup, TypeScript, and Angular 2?

I am currently working on a project called angular2-google-maps-test and I am interested in integrating and expanding upon the JS library found at js-marker-clusterer npm install --save js-marker-clusterer It seems that this library is not structured as ...

Unable to retrieve query parameters from the ActivatedRoute class

I currently have a route set up in the routing module like this: { path: 'warning/:type', component: WarningPageComponent } When the application needs to navigate to the warning page, it makes this call: const navigationExtras: NavigationExtras ...

How can I make the snackbar open multiple times in a row?

Check out this codesandbox I created to show an issue. When you click the button, a MUI snackbar opens. However, if you close it and try to reopen it, nothing happens. Do you think the problem is related to how I'm using hooks? Explore the sandbox h ...

The error message "Unable to adjust headers once they have been sent. Angular Universal ExpressJS" appears

I am trying to implement a 404 error response in my Angular 5 component with server-side rendering. In my server.js file, I have set up the following: app.engine('html', (_, options, callback) => { let engine = ngExpressEngine({ bootst ...

Troubleshooting: Socket.io integration in Angular is not functioning within a .then() statement

Upon running this code snippet in a component: const videoholder = <HTMLDivElement>( document.querySelector('#videoholder') ); const myPeer = new Peer(this.userid, { host: '/', ...

Using string replacement for effective search finding: Unleashing the power of substring matching

I have a method that adds an anchor tag for each instance of @something. The anchor tag links to a specific sub URL. Check out the code: private createAnchors(text: string) { return text.replace(/(@[^ @]+)/ig, '<a href="/home/user/$1">$1& ...

Transforming an array of elements into an object holding those elements

I really want to accomplish something similar to this: type Bar = { title: string; data: any; } const myBars: Bar[] = [ { title: "goodbye", data: 2, }, { title: "universe", data: "foo" } ]; funct ...

Tips for denoting unnecessary non-null assertions in Typescript

Incorporated this wrapper (source) into the project I'm currently working on: export function expectToBeDefined<T>( arg: T, ): asserts arg is Exclude<T, undefined> { expect(arg).toBeDefined(); } The objective is to eliminate the usage ...

What is the best way to access a particular value within a nested array in Angular?

As someone new to programming, I'm facing a challenge with one of my school projects. I have a JSON nested array that I got from my ASP.Net API, and I'm trying to extract the speakerID value from this array and add it to another array using Angul ...

Updating and saving data in Ag-Grid with server communication

Is it possible to create a grid using Ag-Grid on Angular that fetches data from a local JSON file? And how can the edited row data be saved and sent to the server or back to the local JSON file? In summary, I would like to know how to save edited row data ...

Error TS2322: The specified type Login cannot be assigned to the given type

I've been facing an issue while working on my app in react native. The error message I keep encountering is as follows: TS2322: Type 'typeof Login' is not assignable to type ScreenComponentType<ParamListBase, "Login"> | undefined Type ...

Finding the number of elements in a FirebaseListObservable involves accessing the `length` property

One of the tasks in my Angular 2 application involves retrieving data from a Firebase database and storing it in a FirebaseListObservable. I have a method called getStatus that is supposed to determine the number of elements in this FirebaseListObservable. ...

Refine the observable data

Trying to filter a list of items from my Firebase database based on location.liked === true has been a challenge for me. I've attempted using the traditional filter array method but have not had success. Can anyone suggest an alternative method to acc ...

Google Maps API Version 3 now allows for custom overlays to be hidden when they overlap

I have implemented multiple custom overlays on a map for various cities and I am trying to manage the overlapping ones by hiding or collapsing them. My goal is to display and expand overlays with the highest population whenever there is available space. M ...