«маршрутизатор-розетка» — это веб-компонент, затем добавьте «CUSTOM_ELEMENTS_SCHEMA», когда я буду писать модульное тестирование

#javascript #angular #typescript #karma-jasmine #angular-test

Вопрос:

Как вы можете видеть, я тестирую приложение с помощью модульного тестирования в angular7, когда бы я ни работал ng test . Я получаю проблему, как будто router-outlet это веб-компонент, затем добавьте CUSTOM_ELEMENTS_SCHEMA в @NgModule.schemas этот компонент, чтобы подавить это сообщение, и проблема связана с компонентом приложения и компонентом группы пациентов, где они называются друг другом в тестовом приложении, пожалуйста, посмотрите.

 patient-group.component.spec.ts
 

Здесь все тестирование проходит здесь, и я включаю все импортные данные, необходимые для этого приложения, пожалуйста, проверьте.

 import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import {tick, fakeAsync} from '@angular/core/testing';
import { Location} from '@angular/common';

import { PatientGroupComponent } from './patient-group.component';
import { Router, RouterOutlet, RouterModule } from "@angular/router";
import { RouterTestingModule} from  '@angular/router/testing';
import  { HttpClientTestingModule} from '@angular/common/http/testing';
import { AppComponent} from '../app.component';

describe('PatientGroupComponent', () => {
  let location : Location;
  let  router : Router;
  let component: PatientGroupComponent;
  let fixture: ComponentFixture<PatientGroupComponent>;
  let fixture1;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports : [RouterTestingModule,RouterModule, HttpClientTestingModule],
      declarations: [ PatientGroupComponent , AppComponent],
      providers : [ RouterOutlet , Router,
         { provide: Router, useClass: RouterModule }
      
      ]
    })
    .compileComponents();

     location = TestBed.get(Location);
     router = TestBed.get(Router);
     fixture1 = TestBed.createComponent(AppComponent);
    router.initialNavigation();

  }));

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

  it('should navigate to  /patientGroup', fakeAsync(()=>{
    router.navigate(['']);
    tick();
    expect(location.path()).toBe('/patientGroup');
  }))

  it('should create', () => {
    const btn = fixture.debugElement.nativeElement.querySelector('group-btn');
    btn.click();
    const h1 = fixture.debugElement.nativeElement.querySelector('group-data')
    expect(h1.innerHTML).toBeTruthy();
  });
});

patient-group.component.html

<form>
    <div *ngIf = "data">  
        <div *ngFor="let arrayList of data let index = i" style="text-align: center;">
            <span style="font-size: 30px;">[</span><span *ngFor="let arrayList2 of arrayList">
                <span style="font-size:30px !important; color: red; margin: 10px;"
                contenteditable="true" [ngModelOptions]="{standalone: true}"   [(ngModel)] = "data[i]" ngDefaultControl >{{arrayList2}}</span>
            </span><span style="font-size: 30px;">]</span>
        </div>

        <div style="text-align: center;">
            <button class="group-btn"
                style="padding: 22px;color: white; font-size : 20px;background-color: blue;border-radius: 50%; margin: 20px 0px;"
                (click)="getPatientGroups()">Click for Patient groups</button>
        </div>

        <h1 class="group-data" *ngIf="patientData >= 0" style="color: green; text-align: center;"> The Patient Group <span
                *ngIf="patientData > 1">'s</span> are : <span style="color: black;">{{patientData}}</span></h1>
    </div>
</form>


app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule,Routes } from '@angular/router';



import { AppComponent } from './app.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MatDialogModule} from '@angular/material/dialog';
import {MatIconModule} from '@angular/material/icon';
import { chatSupportService } from './services/chat-support.service';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import {MatFormFieldModule, MatFormFieldControl} from '@angular/material/form-field';
import {MatInputModule} from '@angular/material/input';
import { HttpClientModule,HTTP_INTERCEPTORS} from '@angular/common/http';
import {MatButtonModule, MatCheckboxModule} from '@angular/material';

import { TokenInterceptor } from './app.interceptor';
import { PatientGroupComponent } from './patient-group/patient-group.component';
//import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/compiler/src/core';

const routes : Routes = [
  { path : '', redirectTo : 'patientGroup', pathMatch : 'full'},
  { path : 'patientGroup', component : PatientGroupComponent}
]

@NgModule({
  declarations: [
    AppComponent,
    PatientGroupComponent,
    
    
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routes),
    MatFormFieldModule,
    BrowserAnimationsModule,
    MatInputModule,
    MatDialogModule,
    MatIconModule,
    HttpClientModule,
    MatButtonModule, 
    MatCheckboxModule,
    FormsModule, ReactiveFormsModule
    
    
    
  ],
  entryComponents:[
   
    
    

  ],
  providers: [chatSupportService,
  
    {
      provide: HTTP_INTERCEPTORS,
      useClass: TokenInterceptor,
      multi: true
    },



  ],
  //schemas : [CUSTOM_ELEMENTS_SCHEMA],
  
  bootstrap: [AppComponent]
})
export class AppModule { }


app.component.html
 

Это компонент приложения, который я здесь не использую.
Но в main.component.html подай, когда я это сделаю . Он показывает ошибки:

 If 'router-outlet' is an Angular component, then verify that it is part of this module.
If 'router-outlet' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.


<div>
  <router-outlet></router-outlet>
</div>
 

Ответ №1:

Пожалуйста, попробуйте изменить переменную маршрута на массив:

 const routes : Routes = [
  { path : '', redirectTo : 'patientGroup', pathMatch : 'full'},
  { path : 'patientGroup', component : PatientGroupComponent}
]
 

Комментарии:

1. и все же у меня та же проблема