角度2触发自定义事件以进行测试

时间:2017-05-18 12:30:01

标签: angular unit-testing jasmine

我正在尝试编写一个单元测试,检查我是否可以处理自定义事件并验证我是否发回了相同的事件

似乎我的活动没有被触发或处理,我不能说

这是组件:

@Component({
  selector: 'sites',
  templateUrl: './sites.component.html',
  styleUrls: ['./sites.component.css'],

})
export class SitesComponent implements OnInit {

  @Input()
  sites : Site[];

  @Output()
  selectedSiteEvent = new EventEmitter();

  constructor() {
  }

  ngOnInit() {
  }

  handleEvent(event: Event){
    console.log("ici ici ici ");
    this.selectedSiteEvent.emit(event);
  }


}

模板:

<div layout="columns" class="sites">
  sites
  <site *ngFor='let occur of sites' [site]="occur" (selectedSiteEvent)="handleEvent($event)">
  </site>

</div>

测试用例:

describe('SitesComponent', () => {
  let component: SitesComponent;
  let fixture: ComponentFixture<SitesComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ SitesComponent, MockSite ]
    })
    .compileComponents();
  }));

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

  it('should raise selectedSiteEvent event when child output this event', () => {
    spyOn(component.selectedSiteEvent, 'emit');



    let de: DebugElement = fixture.debugElement.query(By.css('.sites'));
    de.triggerEventHandler('selectedSiteEvent', null);

    fixture.detectChanges();


    expect(component.selectedSiteEvent.emit).toHaveBeenCalled()
  });

});

0 个答案:

没有答案