所以我有这个组件,当单击它作为独立的Angular组件时,应该显示一个绿色的选中标记,我想对其进行测试,例如使用以下代码:
xit('should show check icon after click', () => {
component.agendaItem = item1;
fixture.detectChanges();
const de = fixture.debugElement.query(By.css('li'));
de.triggerEventHandler('click', null);
fixture.detectChanges();
const testEl = de.query(By.css('.fa.fa-check'));
expect(component.selected).toBe(true);
expect(testEl).toBeTruthy();
});
(我暂时禁用了规范)。问题是,有时第二个元素testEl
是真实的,有时不是,并且我不知道在哪种情况下。另外,我有时似乎会对其他单元测试产生影响,因为该错误也可能再次在afterAll()
中引发,而不是一致的行为,仅在我尝试查询组件的模板时才会发生。
使用Jasmine 3.4.0和Karma 4.2.0切换到Angular 8后,我只有这个错误,当我禁用Jasmine的随机测试时,该错误也消失了。
组件:
import {Component, Input, OnInit} from '@angular/core';
@Component({
selector: 'm2m-agenda-item',
template: `
<li class="list-group-item mb-1" [class.m2m-agenda-item-selected]="selected" (click)="toggleSelect($event)">
<div class="d-flex justify-content-between">
<div>
<h6>{{ agendaItem?.agendaItem }}</h6>
<br>
<p [innerHTML]="agendaItem?.agendaItemDescription"></p>
</div>
<div class="d-flex flex-column justify-content-center">
<div><i *ngIf="selected" class="fa fa-check fa-lg text-secondary"></i></div>
</div>
</div>
</li>
`,
styleUrls: ['./find-invitation.scss']
})
export class AgendaItemComponent implements OnInit {
@Input() agendaItem;
selected = false;
constructor() {
}
ngOnInit() {
}
toggleSelect($event: MouseEvent) {
$event.preventDefault();
this.selected = !this.selected;
}
}
,测试设置如下:
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [AgendaItemComponent]
})
.compileComponents();
fixture = TestBed.createComponent(AgendaItemComponent);
component = fixture.componentInstance;
fixture.detectChanges();
}));
感谢帮助!