与提供商进行单元测试角度/离子指令

时间:2018-11-28 07:30:20

标签: angular ionic-framework

我正在尝试测试我的SwingDirective

@Directive({
  selector: '[swing]' 
})
export class SwingDirective {
  constructor(private domCtrl: DomController, private renderer: Renderer2, public element: ElementRef ) {
  }
}

我的TestBed如下所示

let RendererMock = jasmine.createSpy("renderer");
let ElemRefMock = jasmine.createSpy("elemRef");
let DomControllerMock = jasmine.createSpy("domCtrl");
@Component({
  template: `  <div class="stack"  swing [positionChange]="positionChange"  >
                </div>
   `
})
class TestComponent { }
describe('Component: Root Component', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [SwingDirective,TestComponent],
      providers: [
      {provide: Renderer2, useValue: RendererMock },
      {provide: ElementRef, useValue: { nativeElement: "element"  }},
      {provide: DomController, useValue: DomControllerMock }
      ],
      imports: [
      IonicModule.forRoot(TestComponent)
      ]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(TestComponent);
    comp    = fixture.componentInstance;
    directive = fixture.debugElement.query(By.directive(SwingDirective)).injector.get(SwingDirective);
  });
})

我创建了TestComponent,它使用swing选择器模拟了我的真实组件。我嘲笑了ngModule provider数组中的指令所需的provider。我的测试运行没有任何错误,但没有达到预期。当我console.log(directive.element)记录它的一个ElementRef实例而不是我提供的{ nativeElement: "element" }}时。

事实上,如果我删除所有提供程序并传递一个空数组,它仍然可以正常工作,并且会自动注入Angular提供程序。情况如何?即使providers数组为空,DI也会如何发生?

0 个答案:

没有答案