Подтвердить что ты не робот

Angular2 Материал "md-icon" не является известным элементом с кармой/жасмином

Я работаю над приложением Angular2, используя @angular/материал 2.0.0-alpha.11-3 angular -cli 1.0.0-beta.19-3 карма 1.2.0 карма-жасмин 1.0.2

Запуск работает отлично, но несколько тестов, в которых шаблон имеет кнопку с ошибкой md-icon с ошибками шаблона:

ERROR: 'Unhandled Promise rejection:', 'Template parse errors:
'md-icon' is not a known element:
1. If 'md-icon' is an Angular component, then verify that it is part of this module.                                
2. If 'md-icon' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message

My app.module.ts:

import { MaterialModule } from '@angular/material';

@NgModule({
  declarations: [
    AppComponent,
    LinearProgressIndicatorComponent,
    MyNewDirectiveDirective,
    MyNewServiceDirective,
    HeaderComponent,
    MenuComponent,
    WatchpanelComponent,
    InputComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    NgbModule.forRoot(),
    MaterialModule.forRoot(),
  ],
  exports: [ MaterialModule ],
  providers: [LocalStorage],
  bootstrap: [AppComponent]
})
export class AppModule { }

watchpanel.component.spec.ts:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { WatchpanelComponent } from './watchpanel.component';

describe('WatchpanelComponent', () => {
  let component: WatchpanelComponent;
  let fixture: ComponentFixture<WatchpanelComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ WatchpanelComponent ] // declare the test component
    })
    .compileComponents();

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

  }));

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

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

Как я понял, это @angular/material теперь содержит единственный модуль, который необходимо импортировать, MaterialModule. Я попытался импортировать MdIconModule из @angular2 -material/icon без успеха. Что я делаю не так? Спасибо заранее

4b9b3361

Ответ 1

Импортирование MaterialModule, как было предложено yurzui, и создание компонента ПОСЛЕ того, как обещание возвращается, решено. Спасибо yurzui

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { WatchpanelComponent } from './watchpanel.component';
import { FormsModule } from '@angular/forms';
import { MaterialModule } from '@angular/material';

describe('WatchpanelComponent', () => {
  let component: WatchpanelComponent;
  let fixture: ComponentFixture<WatchpanelComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ MaterialModule.forRoot() ],
      // forRoot() deprecated
      // in later versions ------^
      declarations: [ WatchpanelComponent ] // declare the test component
    })
    .compileComponents().then(() => {
      fixture = TestBed.createComponent(WatchpanelComponent);
      component = fixture.componentInstance;
      fixture.detectChanges();
    });

  }));

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

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

Ответ 2

Изменения в новых версиях Angular Материал после ответа @javahaxxor. Я решил эту проблему при импорте тех же модулей, что и в AppModule (мне также нужны формы здесь):

import {
  MatButtonModule,
  MatCardModule,
  MatIconModule,
  MatInputModule,
  MatProgressSpinnerModule,
  MatDialogModule,
  MatCheckboxModule
} from '@angular/material';

// ... not important

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ WelcomeComponent ],
      imports: [
        NoopAnimationsModule,
        FormsModule,
        ReactiveFormsModule,
        MatButtonModule,
        MatCardModule,
        MatIconModule,
        MatInputModule,
        MatProgressSpinnerModule,
        MatDialogModule,
        MatCheckboxModule
      ],
      providers: [
        // ...
      ]
    })
    .compileComponents();
  }));

Ответ 3

md-icon больше не доступен в последних версиях Angular Material. Все теги/элементы теперь имеют префикс "mat" вместо "md". Итак, <md-icon>..becomes.. <mat-icon>