“无法解析MdDialogRef的所有参数:(?)”测试NG2材料对话框组件时出错

时间:2016-12-21 23:02:53

标签: unit-testing angular typescript

我有一个登录组件如下:

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();
    });
  }

}

我对此组件的测试规范如下:

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();
    });
});

我尝试了一百万种不同的东西,无论我做什么,我都会收到以下错误:

  

无法解析MdDialogRef的所有参数:(?)

这是MdDialogRef的代码,它只有1个参数OverlayRef。我错过了什么?

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>;
}

编辑:从@ Ryan的评论中获取线索,我尝试完全删除MdDialogRef提供程序并收到以下错误:

  

无法解析OverlayRef的所有参数:(?,?,?)

这让我相信问题实际上是w / MdDialogRef试图解决OverlayRef,而不是W / MdDialogRef本身。

工作示例根据Yurzui的建议,以下代码是实际工作代码。

    /* 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();
    });
});

2 个答案:

答案 0 :(得分:7)

存在问题 ComponentFactoryResolver is not aware of components compiled via TestBed

根据这个问题,angular2团队通过创建具有entryComponents属性的真实模块来提供解决方法 https://github.com/angular/material2/blob/2.0.0-beta.1/src/lib/dialog/dialog.spec.ts#L387-L402

所以你的测试可以像这样写:

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

答案 1 :(得分:2)

我正常运行代码时遇到同样的错误,即我没有编写测试用例。

我发现主要组件中的行from bs4 import BeautifulSoup import urllib.request from urllib.parse import urlparse import re popup_inspection = "http://www.bobaedream.co.kr/mycar/popup/mycarChart_4.php?zone=C&cno=652691&tbl=cyber" res = urllib.request.urlopen(popup_inspection) html = res.read() soup_inspection = BeautifulSoup(html, 'html.parser') insp_trs = soup_inspection.find_all('tr') for insp_tr in insp_trs: # print(insp_td.text) th = insp_tr.find('th') td = insp_tr.find('td') if td.find('input', checked=''): print(th, ":", td) else: pass 给出了完全相同的错误,一切都没有。