Angular unit testing encounters an error when using the DynamicTestModule

I am currently setting up a unit testing environment using Karma and Jasmine. Here is an example:

describe('ProfileListComponent', () =>  {
let component: ProfileListComponent;

beforeEach(async(() => {
    TestBed.configureTestingModule({
        imports: [
            [RouterModule.forRoot([])],
            FormsModule
        ],
        declarations: [
            ProfileListComponent,
            ProfilesFiltersComponent,
            DatatableComponent,
            ProfileImagePopoverComponent,
            NgbHighlight,
            NgbRating,
            PaginationFooterComponent
        ],
        providers: []
    }).compileComponents();

    TestBed.configureTestingModule({
        declarations: [ ProfileListComponent ]
    })
    .createComponent(ProfileListComponent);
}));


it('should be 4', async(() => {
    expect(component.add(2,2)).toEqual(4);
}))

});

The profile list component contains several child components that had to be imported under declarations. For instance, the ProfilesFiltersComponent uses Angular Forms as shown below:

HTML:

TS

export class ProfilesFiltersComponent implements OnInit {
 filterForm: FormGroup;
}

During testing, I encountered an error regarding binding 'formGroup' in the form component:

Can't bind to 'formGroup' since it isn't a known property of 'form'

To address this issue, I added 'FormGroup' to the declarations section of the test setup:

 declarations: [
    ...
    FormGroup
    ]

This adjustment led to a new error:

Failed: Unexpected value 'FormGroup' declared by the module 'DynamicTestModule'. Please add a @Pipe/@Directive/@Component annotation.

At this point, I am unsure how to proceed and resolve this issue. Any insights?

Answer №1

Eliminate FormGroup from the list of items in declarations.

Experiment with updating the imports to:

imports: [
            RouterTestingModule,
            // It's important to have either FormsModule or ReactiveFormsModule
            FormsModule,
            ReactiveFormsModule
        ],

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

Segment the progress bar into sections

Struggling with an Angular app, and still new to HTML and CSS, I am attempting to create a unique progress bar. I aim to split each section of the progress bar into two subsections with distinct background colors shown in this image: https://i.sstatic.net/ ...

Using Angular, a class can serve as a method within another class

I am new to Angular2 and encountering a problem. I have developed a component called info. In the info.component.ts file, I am initializing objects in the following way: import { Comm } from '../shared/comments'; ... const VASACOM: Comm = { na ...

When a function is passed as an argument in Typescript, it may return the window object instead of the constructor

I'm still getting the hang of typescript, and I've come across a situation where a function inside a Class constructor is calling another function, but when trying to access this within sayHelloAgain(), it returns the window object instead. With ...

The app.module encounters issues with selectors specified in its child module, feature.module, in Angular 5

When working with Angular, my app.component.html is kept simple: <app-child></app-child> The setup in App.module looks like this: import { ChildModule } from './child/child.module'; import { NgModule, Browser } from '@angular/ ...

Dependency Injection: The constructor of the injectable class is called multiple times

There are multiple classes that inject the TermsExchangeService: import {TermsExchangeService} from './terms-exchange.service'; @injectable() export class TermsExchangeComponent { constructor( private termsExchangeService: TermsExchan ...

What steps should I take to eliminate the npm error from appearing in the protractor's logs whenever a spec fails?

I recently began using Protractor with Jasmine for testing an Ionic2 application. However, I have encountered two major issues that I have been unable to resolve despite extensive research: 1.)Whenever any of my specifications fail during testing, the err ...

Leveraging Angular 2 components within ASP.NET websites

I am in the process of transitioning the front-end portion of a website to Angular 2. The current setup involves a large ASP.NET 4.5 website. My plan is to create a separate Angular 2 project to accommodate future growth and eventually replace the ASP.NET ...

How can I effectively pass an array of objects to an interface in React with Typescript?

In my code, I have defined two interfaces as shown below: export interface TableBoxPropsHeader{ name: string, isIconOnly: boolean } export interface TableBoxProps<T> { headerNames: TableBoxPropsHeader[], // some stuff } I am currently fa ...

Incorporating an Angular 2 Directive within the body tag of an

My goal is to create a custom directive that can dynamically add or remove a class from the body element in HTML. The directive needs to be controlled by a service, as I want to manage the visibility of the class from various components. Question: How ca ...

What categories do input events fall into within Vue?

What Typescript types should be used for input events in Vue to avoid missing target value, key, or files properties when using Event? For example: <input @input="(e: MISSING_TYPE) => {}" /> <input @keypress="(e: MISSING_TYPE) = ...

Toggle the visibility of an input field based on a checkbox's onchange event

I am facing a challenge where I need to display or hide an Input/Text field based on the state of a Checkbox. When the Checkbox is checked, I want to show the TextField, and when it is unchecked, I want to hide it. Below is the code snippet for this compon ...

"Checkboxes in the column filter are failing to reflect recent

Imagine a scenario where a column in ag-grid can only have two values, specifically "Yes" and "No" as strings. In ag-grid, there exists a built-in column filter that displays all distinct values of that column with checkboxes. Explore Yes and No options ...

Issue encountered when trying to send an email using Node.js and Express

I've encountered an issue while attempting to send an email upon submitting an HTML form using nodemailer. Every time I click on the submit button, I receive the following error message... TypeError: sendMail is not a function at C:\Users&bso ...

Having trouble importing the "@angular/material" module

I'm completely new to working with the MEAN stack and currently running into issues with Angular's material module. I am attempting to bring in the "@angular/material" module into my code, but encountering an error each time I try to import it. T ...

The 'component' property is not found in the 'IntrinsicAttributes' type in this context

I am facing an issue with a component that is not compiling properly: export default function MobileNav({routes, currentRouteIndex, handlePressedRoutedIndex}: MobileNavProp) { ... return ( <React.Fragment> ... ...

Tips for preventing unnecessary dependencies from being installed in an Angular 10 application

I've been working on a project using Angular 10. Surprisingly, my package.json doesn't mention anything about @babel. However, every time I run npm install, an error occurs: npm ERR! 404 Not Found - GET http://private_repo/repository/npm-all/@bab ...

How to use Angular template syntax to assign an async array to multiple variables

When working in JS, there is a clever method for assigning values from an array to new variables with ease: let [a, b, c] = [1, 2, 3]; // a = 1, b = 2, c = 3 I started thinking about whether I could achieve a similar elegant solution using Angular's ...

Explaining the distinction between include and rootDir in tsconfig.json

According to the information provided, include defines an array of filenames or patterns that are to be included in the program during the compilation process. On the other hand, rootDir specifies the path to the folder containing the source code of the ap ...

Mock a single method within an Angular service

Within my Angular service, I have a method that listens for state changes and returns an observable. However, other methods within the same service handle transformation logic: ngOnInit() { this.isLoading = true; this.myService.stateListener().sub ...

There was an issue locating the moment/ts3.1-typings/moment module

Encountering an ERROR after updating Angular version: Could not resolve moment/ts3.1-typings/moment in node_modules/ngx-daterangepicker-material/ngx-daterangepicker-material.d.ts ...