测试Angular 2材料对话框组件时出错

时间:2017-05-08 03:39:04

标签: angular karma-jasmine angular-material2

当我运行测试时,我得到"无法解析MdDialogRef的所有参数:(?,?)"错误。请帮忙。

请参阅以下代码以供进一步参考。

MyComponent.spec.ts

const Promise = require('bluebird');
const execFile = Promise.promisify(require('child_process').execFile, {multiArgs: true});

execFile('find', [IMAGE_DIR]).then(function(args) {
    let stdout = args[0];
    let stderr = args[1];
    // process result here
}).catch(function(err) {
    // handle error here
}); 

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

1 个答案:

答案 0 :(得分:2)

在Angular [https://github.com/angular/angular/issues/10760]

中打开问题

按评论分辨率:

&#34;依赖于ComponentFactoryResolver正确填充的测试需要 声明&#34; entryComponents&#34;通过configureTestModule(或导入一个模块 这样做)。这样您就可以测试您的模块是否正确/测试方式 用户将使用您的模块。&#34;

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