“No provider for MdDialogRef!”

余生长醉 提交于 2019-12-03 23:46:51

You may have tried to use your dialog component in a template like this:

<pizza-dialog ...></pizza-dialog>

Delete that from your template and open the dialog using MdDialog.open() as is done here:

@Component({
  selector: 'pizza-component',
  template: `
  <button type="button" (click)="openDialog()">Open dialog</button>
  `
})
export class PizzaComponent {

  dialogRef: MdDialogRef<PizzaDialog>;

  constructor(public dialog: MdDialog) { }

  openDialog() {
    this.dialogRef = this.dialog.open(PizzaDialog, {
      disableClose: false
    });

    this.dialogRef.afterClosed().subscribe(result => {
      console.log('result: ' + result);
      this.dialogRef = null;
    });
  }
}

This code was copied from: https://github.com/angular/material2/blob/master/src/lib/dialog/README.md

You must not change your implementation. You can provide a Mock for the MdDialogRef. In the following example I fake the MdDialogRef with the MdDialogRefMock class and register it in the providers section:

import { async, ComponentFixture, TestBed } from "@angular/core/testing";
import { CUSTOM_ELEMENTS_SCHEMA } from "@angular/core";
import { MessageBoxYesNoComponent } from "./message-box-yes-no.component";
import { MdDialogRef } from "@angular/material";

class MdDialogRefMock {
}

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ MessageBoxYesNoComponent ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
      imports: [
      ],
      providers: [
        { provide: MdDialogRef, useClass: MdDialogRefMock }
      ]
    })
    .compileComponents();
  }));

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

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

If you are using Jasmine, you can also create a Spy instead of creating the Fake-Class:

let mdDialogSpy = jasmine.createSpy('MdDialogRef');

Remove <pizza-dialog ...></pizza-dialog> from the template, it only require the button that open the Dialong because in the code you set the relation with the dialog.

Add MdDialogRef to providers of your module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!