Javascript TypeError:无法读取属性';调度事件';空的
Angular中的一个书面emit方法测试用例现在面临一个问题是TypeError:无法读取null的属性“dispatchEvent” 获取单击事件结束调用以发出方法。 子组件Html文件 article.htmlJavascript TypeError:无法读取属性';调度事件';空的,javascript,angular,typescript,Javascript,Angular,Typescript,Angular中的一个书面emit方法测试用例现在面临一个问题是TypeError:无法读取null的属性“dispatchEvent” 获取单击事件结束调用以发出方法。 子组件Html文件 article.html <a (click)="edit(item)" class="mat-card-title" style="cursor: pointer">{{ item.title }}</a> TypeError:无法读取null的属性“dispatchEvent”
<a (click)="edit(item)" class="mat-card-title" style="cursor: pointer">{{ item.title }}</a>
TypeError:无法读取null的属性“dispatchEvent”您应该将
ElementRef
作为fixture的类型:
大概是这样的:
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();
您应该提到
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();
您提供的示例代码使用fixture.detectChanges(),在您的示例中,fixture.detectChanges()应该是fixture2.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'});
});
我希望这会有所帮助。您提供的示例代码使用fixture.detectChanges(),在您的情况下,fixture.detectChanges()应该是fixture2.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'});
});
我希望这有帮助