The element mat-divider in Angular is unrecognized

While testing a popup component in Angular, I encountered an error message that says:

'mat-divider' is not a known element: 1. If 'mat-divider' is an Angular component, then verify that it is part of this module. 2. If 'mat-divider' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

Even though I imported it in the @NgModule, here is the code snippet:

@NgModule({
  declarations: [
    AppComponent,
    AdminTopMenuComponent,
    SvGameCardComponent,
    SvCreationPopupComponent,
    MockPopupComponent,
MyDialogComponent,
FvCreationPopupComponent,
    GameModesComponent,
    LinkTestComponent,
    UserComponent,
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    AppRoutingModule,
    FormsModule,
    ReactiveFormsModule,
    MatDialogModule,
BrowserAnimationsModule,
MatButtonModule,
MatCheckboxModule,
    MatTableModule,
    MatDividerModule,
    MatInputModule,
    MatSelectModule,
    MatFormFieldModule,
    MatCardModule,
    AppRoutingModule,
    RouterModule,
  ],
  exports: [
      MatDividerModule,
      MatFormFieldModule,
  ],
  providers: [BasicService],
  bootstrap: [AppComponent],
  entryComponents: [
    MyDialogComponent,
    SvCreationPopupComponent,
    FvCreationPopupComponent,
    ]
})

export class AppModule {

}

@Component({
  selector: 'app-fv-creation-popup',
  templateUrl: './fv-creation-popup.component.html',
  styleUrls: ['./fv-creation-popup.component.css']
})
export class FvCreationPopupComponent implements OnInit {

  constructor(
    public dialogRef: MatDialogRef<FvCreationPopupComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any) { }

  ngOnInit() {
    
  }
  
  submit(): void {
    console.log("Submit fv-gameCard not implemented")
  }

  close(): void {
    this.dialogRef.close();
  }
  gameType: string[] = ["Formes géométriques","Thématique"];
  
}

import { /*async,*/ async, ComponentFixture, TestBed } from "@angular/core/testing";

import { MatDialogModule, MatDialogRef, MAT_DIALOG_DATA } from "@angular/material";
import { FvCreationPopupComponent } from "./fv-creation-popup.component";

describe("FvCreationPopupComponent", () => {
    let component: FvCreationPopupComponent;
    let fixture: ComponentFixture<FvCreationPopupComponent>;

    beforeEach(async(() => {
        const mockDialogRef = {
            close: jasmine.createSpy("close"),
        };

        TestBed.configureTestingModule({
        imports: [MatDialogModule],
        declarations: [ FvCreationPopupComponent ],
        providers: [{ provide: MatDialogRef, useValue: {mockDialogRef} }, { provide: MAT_DIALOG_DATA, useValue: {} } ]})
        .compileComponents();
    }));

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

    it("should create", () => {
        expect(component).toBeTruthy();
    });

});

Answer №1

Ensuring that the MatDividerModule is included in your testing module is crucial. Similarly, all other modules used in the component must also be included. Here is an example of how to achieve this:

import { MatDialogModule, MatDialogRef, MAT_DIALOG_DATA } from "@angular/material";
import { FvCreationPopupComponent } from "./fv-creation-popup.component";

describe("FvCreationPopupComponent", () => {
    let component: FvCreationPopupComponent;
    let fixture: ComponentFixture<FvCreationPopupComponent>;
    // const mock: MatDialogRef<FvCreationPopupComponent> = new MatDialogRef<FvCreationPopupComponent>(null, null) ;

    beforeEach(async(() => {
        // const data: MyDialogComponent = null;
        // data.message = "Dialog Message";
        // tslint:disable-next-line:typedef
        const mockDialogRef = {
            close: jasmine.createSpy("close"),
        };

        TestBed.configureTestingModule({
        imports: [MatDialogModule, MatDividerModule, ...],
        declarations: [ FvCreationPopupComponent ],
        providers: [{ provide: MatDialogRef, useValue: {mockDialogRef} }, { provide: MAT_DIALOG_DATA, useValue: {} } ]})
        .compileComponents();
    }));

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

    it("should create", () => {
        expect(component).toBeTruthy();
    });

});

Answer №2

The issue I encountered was due to not including my sub component in app.module.ts

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

What is the best approach for injecting services (local and API) in Angular 13 based on different environments (local and QA)?

api-local.service.ts import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { LoginRequest } from '../login/login-request'; @Injectable({ providedIn: 'root&ap ...

Automatically pass on parameters from a universal function

If I have an object with functions that return numbers: const obj = { foo() { return 1; } bar() { return 2; } baz(num: number) { return num; } } The expected output of typeof obj would be: { foo: () => number; bar: () => number; baz ...

The external typing file encounters an issue when trying to locate the relative path to its own index.d.ts file

While working on my project and using react-color as a dependency, I encountered an issue with the tsc import failing. The error message displayed: node_modules/@types/react-color/lib/components/sketch/Sketch.d.ts(2,41): error TS2307: Cannot find module & ...

Obtain redirected JSON data locally using Angular 5

Currently, I am working on retrieving JSON data which will be sent to my localhost through a POST method. The SpringBoot API controller will validate the JSON content before forwarding it to my localhost. My task is to intercept this JSON data when it is t ...

What could be causing TypeScript to not locate my custom package?

I decided to create a fork of an existing package and released it with a new, distinct name: https://www.npmjs.com/package/feed-media-fork After tagging a new version, setting up a release on GitHub, and running yarn add feed-media-fork or the equivalent ...

Having trouble with my first Angular 2 application that is meant to print "My First Angular 2 App"?

I have created a program to display the message "My First Angular 2 App", but I am facing issues with the output. Can anyone help me identify where I might be going wrong? environment_app.component.ts import { AnotherComponent } from './anotherCompo ...

Can a function be annotated in order to inform the TypeScript compiler that it has verified the type of a class property?

How can I annotate `readText` in the code snippet below to assure the compiler that `this.text` is of type `string` and not `string | undefined`? type MyResponse = { text: () => Promise<string>; }; class ResponseVerfier { response: MyRespons ...

What is the best way to incorporate TypeScript into a simple JavaScript project and release it as a JavaScript library with JSDoc for TypeScript users?

Issue: I have encountered difficulties finding an efficient solution for this. Here's a summary of what I attempted: To start, ensure that allowJs and checkJs are both set to true in the tsconfig.json, then include the project files accordingly. Ty ...

When should services be included within providers?

After completing a small Angular 2 project, I compared my work with the provided code and realized that in the app.module.ts file, only one of the two services I created was included by the tutor. users.service.ts import { Component, Injectable } fro ...

Error with the type of CanvasGradient in the NPM package for converting text to image

I attempted to generate an image using a specific text by utilizing npm's text-to-image package, but encountered an error during typescript compilation. The errors I encountered upon running the typescript compilation command are related to files with ...

Unit testing in Angular 2: Triggering hover events

In my setup, I have a template for a specific component (MyCmp) that looks like this <template ngFor let-r [ngForOf]="range" let-index="index"> <span>{{ index < 5 ? 'Y' : 'N' }}, {{r.data}}</span> <i (mousee ...

Leveraging Angular2's observable stream in combination with *ngFor

Below is the code snippet I am working with: objs = [] getObjs() { let counter = 0 this.myService.getObjs() .map((obj) => { counter = counter > 5 ? 0 : counter; obj.col = counter; counter++; return view ...

Running a desktop Word AddIn using Angular 11.0.5 on MS Office 2016: A Step-by-Step Guide

I am facing an issue with loading my add-ins in the Office desktop version, although it works fine on the online platform. I initially developed the AddIn using Angular 5.2.11 and it worked perfectly. However, after upgrading to Angular 11.0.5, the Add-in ...

Encountering a Selenium error while trying to select and click on the button's ID

Currently, I am experimenting with the Java Selenium client and JBehave to showcase BDD techniques by interacting with a basic web page. While executing the test, my goal is to simply selenium.click("joinButton"); However, I keep encountering a (com.th ...

Maintain synchrony of the state with swiftly unfolding occurrences

I developed a custom hook to keep track of a state variable that increments based on the number of socket events received. However, when I tested by sending 10 simultaneous events, the total value of the state variable ended up being 6, 7, or 8 instead of ...

Learn how to extend components in Typescript and determine necessary arguments. Discover how to apply this knowledge in an Angular use case by extending mat-side-nav

Background: The Angular Material Design component known as mat-side-nav operates in a specific structure for its dynamics: <mat-sidenav-container> <mat-sidenav> </mat-sidenav> <mat-sidenav-content> </mat-sidenav-conten ...

Attempting to utilize Array Methods with an Array Union Type

Currently, I am in the process of refactoring an Angular application to enable strict typing. One issue I have encountered is using array methods with an array union type in our LookupService. When attempting to call const lookup = lookupConfig.find(l =&g ...

Testing a reusable component in Angular using unit testing techniques

Currently, I am creating a test for an AppleComponent which has the following type: <T,U extends BananaComponent<T>>. This component also contains BananaComponent<T>. Target Component export class AppleComponent<T,U extends BananaCom ...

Error encountered: ⨯ Compilation of TypeScript failed

My current project is utilizing Node.js in conjunction with TypeScript An issue has arisen during compilation within my Node.js application: E:\NodeProjects\esshop-mongodb-nodejs\node_modules\ts-node\src\index.ts:859 ret ...

Issue encountered while executing jest tests - unable to read runtime.json file

I've written multiple unit tests, and they all seem to pass except for one specific spec file that is causing the following error: Test suite failed to run The configuration file /Users/dfaizulaev/Documents/projectname/config/runtime.json cannot be r ...