Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Can't resolve all parameters for MdDialogRef: (?)" Error when testing NG2 Material Dialog component

I have a login component as follows:

import { Component, OnInit } from '@angular/core';
import { MdDialogRef } from '@angular/material';

import { AuthService } from '../../core/services/auth.service';

@Component({
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginDialogComponent implements OnInit {

  model: {
    email: string,
    password: string
  };
  error;

  constructor(
    private authService: AuthService,
    private dialogRef: MdDialogRef<LoginDialogComponent>
  ) { }

  ngOnInit() {
    this.model = {
      email: '',
      password: ''
    };
  }

  signin() {
    this.error = null;
    this.authService.login(this.model.email, this.model.password).subscribe(data => {
      this.dialogRef.close(data);
    }, err => {
      this.error = err.json();
    });
  }

}

And I have a test spec for this component as follows:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { MdDialogRef, OverlayRef  } from '@angular/material';

import { AuthService } from '../../core/services/auth.service';
import { LoginDialogComponent } from './login.component';

describe('Component: Login', () => {

    let component: LoginDialogComponent;
    let fixture: ComponentFixture<LoginDialogComponent>;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [
                LoginDialogComponent
            ],
            imports: [],
            providers: [
                AuthService,
                MdDialogRef,
                OverlayRef
            ]
        })
            .compileComponents();
    }));

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

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

I've tried a million different things, and no matter what I do, I get the following error:

Can't resolve all parameters for MdDialogRef: (?)

Here's the code for MdDialogRef, which only has 1 parameter, OverlayRef. What am I missing?

import { OverlayRef } from '../core';
import { Observable } from 'rxjs/Observable';
/**
 * Reference to a dialog opened via the MdDialog service.
 */
export declare class MdDialogRef<T> {
    private _overlayRef;
    /** The instance of component opened into the dialog. */
    componentInstance: T;
    /** Subject for notifying the user that the dialog has finished closing. */
    private _afterClosed;
    constructor(_overlayRef: OverlayRef);
    /**
     * Close the dialog.
     * @param dialogResult Optional result to return to the dialog opener.
     */
    close(dialogResult?: any): void;
    /** Gets an observable that is notified when the dialog is finished closing. */
    afterClosed(): Observable<any>;
}

EDIT: taking a clue from @Ryan's comment, I tried removing the MdDialogRef provider entirely and got the following error:

Can't resolve all parameters for OverlayRef: (?, ?, ?)

This leads me to believe that the problem is actually w/MdDialogRef trying to resolve OverlayRef, not w/MdDialogRef itself.

WORKING EXAMPLE The code below is the actual working code, per Yurzui's suggestion.

    /* tslint:disable:no-unused-variable */

import { NgModule } from '@angular/core';
import { async, TestBed } from '@angular/core/testing';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { MaterialModule, MdDialogModule, MdToolbarModule, MdDialog, MdDialogRef } from '@angular/material';

import { CoreModule } from '../../core/core.module';
import { LoginDialogComponent } from './login.component';

@NgModule({
    declarations: [
        LoginDialogComponent
    ],
    entryComponents: [
        LoginDialogComponent
    ],
    exports: [
        LoginDialogComponent
    ],
    imports: [
        CommonModule,
        CoreModule,
        FormsModule,
        MaterialModule.forRoot(),
        MdDialogModule.forRoot(),
        MdToolbarModule.forRoot()
    ]
})
class LoginDialogSpecModule { }

describe('Component: Login Dialog', () => {
    let component: LoginDialogComponent;
    let dialog: MdDialog;

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [
                LoginDialogSpecModule
            ]
        });
    });

    beforeEach(() => {
        dialog = TestBed.get(MdDialog);
        let dialogRef = dialog.open(LoginDialogComponent);
        component = dialogRef.componentInstance;
    });

    it('should create', () => {
        expect(component).toBeTruthy();
    });
});
like image 440
Dr. Hilarius Avatar asked Jan 05 '23 21:01

Dr. Hilarius


1 Answers

There is an issue ComponentFactoryResolver is not aware of components compiled via TestBed

According to this problem angular2 team offers workaround by creating real module with entryComponents property https://github.com/angular/material2/blob/2.0.0-beta.1/src/lib/dialog/dialog.spec.ts#L387-L402

So your test could write like this:

import { MdDialog, MdDialogModule } from '@angular/material';   

@NgModule({
    declarations: [TestComponent],
    entryComponents: [TestComponent],
    exports: [TestComponent],
})
class TestModule { }

describe('Component: Login', () => {
    let component: TestComponent;
    let dialog: MdDialog;

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [TestModule, MdDialogModule]
        });
    });

    beforeEach(() => {
        dialog = TestBed.get(MdDialog);
        let dialogRef = dialog.open(TestComponent);

        component = dialogRef.componentInstance;
    });

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

Plunker Example

like image 100
yurzui Avatar answered Jan 13 '23 10:01

yurzui