2017-05-08 38 views
1

当我运行测试时,我得到“无法解析MdDialogRef的所有参数:(?,?)”错误。请帮忙。在测试Angular 2材质对话框组件时得到错误

请参考下面的代码进一步参考。

MyComponent.spec.ts

import { async, ComponentFixture, ComponentFixtureAutoDetect, TestBed } from '@angular/core/testing'; 
import { MyComponent } from './my.component'; 
import { MdDialogModule, MdDialog, MdDialogConfig, MdDialogRef } from '@angular/material'; 
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; 

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

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

    beforeEach(async(() => { 
    TestBed.configureTestingModule({ 
     declarations: [MyComponent], 
     imports: [BrowserAnimationsModule, MdDialogModule.forRoot()], 
     providers: [MdDialogRef], 
    }) 
     .compileComponents(); 
    })); 

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

    it('should, have defined component',() => { 
    expect(component).toBeDefined(); 
    }); 
}); 

MyComponent.ts

import { Component } from '@angular/core'; 
import { MdDialog, MdDialogRef } from '@angular/material'; 
@Component({ 
    templateUrl: './mys.component.html' 
}) 

export class MyComponent { 
    constructor(public dialogRef: MdDialogRef<any>) { } 
} 

回答

2

在角[开放问题https://github.com/angular/angular/issues/10760]

分辨率为每点评:

”依赖ComponentFactoryResolver进行正确填充的测试需要 通过configureTestModule声明“entryComponents”(或导入一个 这样做的模块)。这样,您就可以测试你的模块是正确的/测试 用户将如何使用您的模块“

演示Plunkr: https://plnkr.co/edit/Tv5fbtPtsiNhFIJ5QhRf?p=preview

创建的组件:

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

@Component({ 
    selector: 'dialog-component', 
    template: `Can't resolve all parameters for MdDialogRef: (?)` 
}) 
export class TestComponent { 
    constructor(private dialogRef: MdDialogRef<any>) { } 
} 

新增的模块

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

使用的TestModule

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

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

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

     component = dialogRef.componentInstance; 
    }); 

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

谢谢,它的工作原理:) – sandyk

+0

噢欢迎好友:) –

+1

有没有什么办法可以关闭对话框,我试过了'dialog.closeAll()',但它不起作用。因为当我使用ng测试来运行所有测试时,弹出式对话框将停止测试。 –