2017-05-08 57 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測試來運行所有測試時,彈出式對話框將停止測試。 –