#test - MatDialogRef -NullInjectorError

1 messages · Page 1 of 1 (latest)

lucid hearth
#

component

  constructor(
    override dialogRef: MatDialogRef<DialogFormAbsenceComponent>
  ) {

test

  beforeEach(inject([MatDialogRef], async(dep, object) => {
    await TestBed.configureTestingModule({
      declarations: [ DialogFormAbsenceComponent ],
      imports: [MatDialogModule],
      providers: [
        {provide: MatDialogRef, useValue: {}},
        {provide: MAT_DIALOG_DATA, useValue: []},
      ]
    })
    .compileComponents();

error

R3InjectorError(CompilerModule)[MatDialogRef -> MatDialogRef]: 
  NullInjectorError: No provider for MatDialogRef!
true ore
#

MatDialogRef is not a service. It's only available to your component because the dialog services creates one and adds it into the injector of the component at runtime. You should probably provide a mock in your testing module providers, or use the testing utilities provided by Angular Material.

lucid hearth
#

ok i check there ! thks

true ore
#

Wait, I think I went too fast when reading your code. What you have there should work fine. At least, this complete minimal test passes:

import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { Component } from '@angular/core';
import { TestBed } from '@angular/core/testing';

@Component({
  template: 'hello'
})
class DialogFormAbsenceComponent {
  constructor(public dialog: MatDialogRef<DialogFormAbsenceComponent>) {}
}

describe('foo', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [DialogFormAbsenceComponent],
      imports: [MatDialogModule],
      providers: [
        { provide: MatDialogRef, useValue: {} },
        { provide: MAT_DIALOG_DATA, useValue: [] }
      ]
    });
  });

  it('should create', () => {
    const fixture = TestBed.createComponent(DialogFormAbsenceComponent);
    fixture.detectChanges();

    expect(fixture.componentInstance.dialog).toBeDefined();
  });
});

If you need help, post a complete minimal test, just as I did.