TypeError:无法读取null的属性'dispatchEvent'

时间:2019-07-10 07:15:40

标签: javascript angular typescript

现在在Angular中遇到问题的书面出射方法测试用例是TypeError:无法读取null的属性'dispatchEvent'。

获取click事件结束调用以发出方法。 子组件HTML文件

article.html

<a (click)="edit(item)" class="mat-card-title" style="cursor: pointer">{{ item.title }}</a>

viewArticle.spec.ts

 fit('emiter call', () => {
    const fixture2 = TestBed.createComponent(ArticleCarouselComponent);
    const component2 = fixture2.componentInstance;
    spyOn(component2.changeevent, 'emit');
    const nativeElement = fixture.nativeElement;
    const button = nativeElement.querySelector('a');
    button.dispatchEvent(new Event('click'));
    fixture.detectChanges();
    expect(component2.changeevent.emit).toHaveBeenCalled();
  });

TypeError:无法读取null的属性“ dispatchEvent”

2 个答案:

答案 0 :(得分:0)

您应该提及ElementRef作为固定装置的类型:

类似这样的东西:

let fixture: ElementRef;
const nativeElement = fixture.nativeElement;
const button = nativeElement.querySelector('a');
button.dispatchEvent(new Event('click'));
fixture.nativeElement.detectChanges();
expect(component2.changeevent.emit).toHaveBeenCalled();

答案 1 :(得分:0)

您提供的示例代码使用的是fixture.detectChanges(),在您的情况下应为fix2.detectChanges()。这可能是问题之一。

fit('emiter call', () => {
    const fixture2 = TestBed.createComponent(ArticleCarouselComponent);
    const component2 = fixture2.componentInstance;
    spyOn(component2.changeevent, 'emit');
    const nativeElement = fixture2.nativeElement;
    const button = nativeElement.querySelector('a');
    button.dispatchEvent(new Event('click'));
    fixture2.detectChanges();
    expect(component2.changeevent.emit).toHaveBeenCalled();
  });

无需间谍活动即可测试事件的另一种方法如下:

    it('should emit correct change event', () => {

    const fixture2 = TestBed.createComponent(ArticleCarouselComponent);
    const component2 = fixture2.componentInstance;

    component2.changeevent.subscribe((event: any) => {

      expect(event.data).toBe('test change event');
    });

   component2.changeevent.emit({data: 'test change event'});

   });

我希望这会有所帮助。