Angular Karma - 错误:没有MdDialogRef的提供者

时间:2017-04-21 19:37:10

标签: angular karma-jasmine angular-cli

我在测试角材料2组件的MdDialog时遇到了问题。问题是我的组件(使用MdDialog)是一个条目组件,我无法使用当前的TestBed配置对其进行测试。当前TestBed配置没有entryComponent属性。

我在这里尝试了所有选项(我创建了一个用于测试的NgModule,覆盖了TestBed配置以及我想出的其他内容):https://github.com/angular/angular/issues/10760

我还查看了角度材料2 MdDialog代码,看看测试是如何做的,但我没有成功。

我没有成功。有没有人在他们的应用程序中成功测试Mdialog组件?你能分享你实施的选项吗?

这是我的示例代码:

#Component

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MdDialogRef } from '@angular/material';

import { MessageService } from './../message.service';
import { MessageRequest } from './../message.model';
import { AuthenticationService } from './../../core/authentication/authentication.service';
import { AuthenticationResponse } from './../../core/authentication/authentication.model';

@Component({
  selector: 'app-message-add',
  templateUrl: './message-add.component.html',
  styleUrls: ['./message-add.component.scss']
})
export class MessageAddComponent implements OnInit {
  messageAddForm: FormGroup;
  currentUser: AuthenticationResponse;
  disabled: boolean;

  constructor(private fb: FormBuilder,
              private dialog: MdDialogRef<MessageAddComponent>,
              private messageService: MessageService,
              private authService: AuthenticationService) {
    this.messageAddForm = fb.group({
      'id': ['', Validators.required],
      'txt': ['', Validators.required]
    });
    this.currentUser = this.authService.getUser();
    this.disabled = true;
  }

  ngOnInit() {
  }

  onDateChange(value: any) {
  }

  onCancel() {
    this.dialog.close();
  }

  onMessageAdd() {
    const newMessage: MessageRequest = {
      user: this.currentUser.userId,
      message: {
        id: this.messageAddForm.value.id,
        txt: this.messageAddForm.value.txt,
      }
    };

    this.messageService.add(newMessage).subscribe((response) => {
      this.dialog.close();
    }, (error) => {
      console.log(`messageService.save: ${JSON.stringify(error)}`);
    });
  }

}

#Component Test

/* tslint:disable:no-unused-variable */
import { async, ComponentFixture, TestBed, inject } from '@angular/core/testing';
import { BrowserModule, By } from '@angular/platform-browser';
import { CommonModule } from '@angular/common';
import { Component, DebugElement, NgModule } from '@angular/core';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { BrowserDynamicTestingModule } from '@angular/platform-browser-dynamic/testing';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import {
  MdButtonModule,
  MdToolbarModule,
  MdInputModule,
  MdMenuModule,
  MdSelectModule,
  MdIconModule,
  MdCardModule,
  MdDialogModule,
  MdOptionModule,
  MdDialog,
  MdDialogRef,
} from '@angular/material';
import { Md2Module } from 'md2';

import { MessageAddComponent } from './message-add.component';

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        CommonModule,
        ReactiveFormsModule,
        FormsModule,
        BrowserAnimationsModule,
        MdButtonModule,
        MdToolbarModule,
        MdInputModule,
        MdMenuModule,
        MdSelectModule,
        MdIconModule,
        MdCardModule,
        MdDialogModule,
        MdOptionModule,
        Md2Module
      ],
      providers: [],
      declarations: [MessageAddComponent]
    }).overrideModule(BrowserDynamicTestingModule, {
      set: {
        entryComponents: [MessageAddComponent],
      },
    });
  }));

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

  it('should create',
    inject([MessageAddComponent], (notificationAddComponent) => {
      expect(notificationAddComponent).toBeTruthy();
    }));
});

2 个答案:

答案 0 :(得分:1)

查看材料的源代码如何测试对话框他们创建一个真实的模块进行测试并将其导入TestBed。 dialog.spec.ts

// Create a real (non-test) NgModule as a workaround for
// https://github.com/angular/angular/issues/10760
const TEST_DIRECTIVES = [
  ComponentWithChildViewContainer,
  PizzaMsg,
  DirectiveWithViewContainer,
  ContentElementDialog,
  DialogWithInjectedData
];

@NgModule({
  imports: [MdDialogModule, NoopAnimationsModule],
  exports: TEST_DIRECTIVES,
  declarations: TEST_DIRECTIVES,
  entryComponents: [
    ComponentWithChildViewContainer,
    PizzaMsg,
    ContentElementDialog,
    DialogWithInjectedData
  ],
})
class DialogTestModule { }

答案 1 :(得分:1)

您需要在测试文件中导入import { MaterialModule } from '@angular/material';

在导入数组中添加MaterialModule

这解决了我的问题。