A guide to simulating ngControl in a Custom Form Control for effective unit testing in Angular

I need some guidance on creating unit tests for a Custom Form Control in Angular 9. The issue arises with this line of code:

constructor(@Self() private ngControl: NgControl)
, which triggers an error:
Error: NodeInjector: NOT_FOUND [NgControl]
. It seems that I must set a value accessor somehow.

I have injected ngControl in the constructor because I will be using it later in my component. This is why I did not opt for the typical implementation with provide: NG_VALUE_ACCESSOR.

I attempted to mock it like so:

beforeEach(async(() => {
    TestBed.configureTestingModule({
        providers: [
            { provide: NgControl, useValue: new FormControlDirective([], [], [], null) }
        ],
        imports: [FormsModule, ReactiveFormsModule]
    }).compileComponents();

However, I encountered the following error:

No valid value accessor for form control with unspecified name attribute
since I am unsure of what should go under the 3rd parameter of the function FormControlDirective, which is:
valueAccessors: ControlValueAccessor[]

Can anyone offer insights on how to properly mock this scenario?

Answer №1

One way to mock it is by following this example:

let ngControlMock: any;

beforeEach(async(() => {
    ngControlMock = jasmine.createSpyObj('ngControl', ['value', /* add other necessary methods here */]);
    TestBed.configureTestingModule({
        providers: [
            { provide: NgControl, useValue: ngControlMock }
        ],
        imports: [FormsModule, ReactiveFormsModule]
    }).compileComponents();

Answer №2

I encountered an issue where my Module with CustomFormControl was not functioning properly due to my failure to include it in the Imports array. By rectifying this oversight, I was able to resolve the problem. Perhaps this solution can benefit someone else facing a similar issue.

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

The type '{}' cannot be assigned to the type '{ title: string; text: string; }'

Upon executing the TypeScript code below, I encountered the following error: Type '{}' is not assignable to type '{ title: string; text: string; }'. Property 'title' is missing in type '{}'. The "article" declara ...

Modification of encapsulated class in Angular is not permitted

Within Angular, a div element with the class "container" is automatically created and inserted into my component's HTML. Is there a way to modify this class to "container-fluid"? I understand that Angular utilizes encapsulation, but I am unsure of how ...

What methods can be used to display data using TypeScript's Optional Chaining feature?

I came across this Try it Yourself TypeScript Optional Chaining example in W3Schools TypeScript Null & Undefined section, and I have attached a screenshot for reference. The example demonstrates that when data is undefined, it displays No Yard. Howeve ...

Tips on enforcing Access-Control-Allow-Origin in a C# webservice hosted on IIS

I have a .net webservice running on IIS 10. My goal is to retrieve data from the backend using an Angular frontend. Access-Control-Allow-Origin is configured in IIS: In addition, customHeaders are set up in my Web.Conf: However, when attempting to acces ...

Challenges with E-commerce Project's Wishlist Feature

Currently, I am working on a project where clicking on the 'fa-heart' icon should toggle between solid and regular states to add or remove an item from the wishlist. However, my attempts so far have resulted in all product icons changing together ...

Guide on utilizing external namespaces to define types in TypeScript and TSX

In my current project, I am working with scripts from Google and Facebook (as well as other external scripts like Intercom) in TypeScript by loading them through a script tag. However, I have encountered issues with most of them because I do not have acces ...

What's the best approach for revalidating data with mutate in SWR?

Whenever a new album is created in my app, the post request response includes an updated list of all albums. To enhance the user experience, I wanted the newly created content to automatically show up without requiring a page refresh. Although I am famil ...

Searching within an Angular component's DOM using JQuery is restricted

Want to incorporate JQuery for DOM manipulation within Angular components, but only want it to target the specific markup within each component. Trying to implement Shadow DOM with this component: import { Component, OnInit, ViewEncapsulation } from &apo ...

Verify if the array entries match

Within my select element, I populate options based on an array of values. For example: [{ name: 'A', type: 'a', }, { name: 'B', type: 'b', }, { name: 'B', type: 'b', }, { name: &apos ...

Encountering CORS Error Despite Having CORS Enabled in Nest.js/Angular Application

Currently, I am in the process of developing a small calculator application as a means to gain expertise in Nest.js and Angular. In order to achieve this, I have established a server that hosts a basic web API equipped with several endpoints. One particula ...

Mapping Interface Types in Typescript

I am currently exploring the correct method to map Interface record value types to the appropriate function type. function stringCompose(): string { return '' } function numberCompose(): number { return 0 } interface Demo { stringVal ...

Issue with passing parameters to function when calling NodeJS Mocha

I have the following function: export function ensurePathFormat(filePath: string, test = false) { console.log(test); if (!filePath || filePath === '') { if (test) { throw new Error('Invalid or empty path provided'); } ...

Fetching data before the Angular app is fully loaded

I need a solution to initiate a service when my app loads. If the service fails, I want to display an error message instead of continuing to load the app. I have read about using APP_INITIALIZER, but it doesn't seem to fit my requirements. In my Angu ...

The declaration file for module 'react/jsx-runtime' could not be located

While using material-ui in a react project with a typescript template, everything is functioning well. However, I have encountered an issue where multiple lines of code are showing red lines as the code renders. The error message being displayed is: Coul ...

The data in Angular2 service is not being saved consistently

I'm diving into Angular for the first time and following along with this tutorial. One of the key features of my Angular app is the CartService, which handles my shopping cart, while the CartComponent displays it in the navbar, and the CartReviewComp ...

Guide on Implementing Class on Dropdown in AngularFollow these steps to effectively utilize the

Currently, I am facing an issue with my Angular project. I am trying to implement a Directive that activates a dropdown menu. However, the 'open' class is deprecated in Bootstrap 3, and I am using Bootstrap 5. How can I transition to the 'sh ...

Discover the type of generic keyof in TypeScript

My types implementation is structured as follows: type GenericType<T, K extends keyof T = keyof T> = { name: K; params: T[K] } type Params = { a: 1; b: 2; } const test: GenericType<Params> = { name: "a", params: 2 } ...

TypeScript Compile Error: The property is not available in the 'IStateParamsService' type

My client project heavily utilizes TypeScript. Currently, I am encountering a technical issue. Within my HTML code, I have an anchor tag as shown below: <a class="btn btn-default mrm" ui-sref="course-detail({courseId: '{{c.Id}}'})">Detail ...

Switching between different types of generic functions in typescript

Is there a way to convert between these two types of generic functions: type Foo=<S>(a: S) => S type FooReturnType = ReturnType<Foo> // unknown type Bar<S> = { (a: S): S } type BarReturnType = ReturnType<Bar<string> ...

Using @carbon/react in conjunction with Next.js version 13 leads to unconventional styling

Here's what I did to set up my Next.js application: npx create-next-app@latest I then installed the necessary package using: npm i -S @carbon/react The global styles in app/globals.scss were customized with this code snippet: @use '@carbon/reac ...