我有一个简单的功能,可以在点击事件上显示和隐藏下拉选单。这是HTML代码
<div (click)="toggleDropdown()" id="game-category">Show/Hide menu</div>
<div >
<app-category *ngIf="isShown" [filtersList]="categories">
</app-category>
</div>
该函式将相反的值设定为组件的属性值。
isShown = false;
toggleDropdown(): void {
this.isShown = !this.isShown;
}
一切正常,但是当我运行测验时出现错误。这是测验代码:
describe('CreateGameComponent', () => {
let component: CreateGameComponent;
let fixture: ComponentFixture<CreateGameComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
CommonModule,
],
declarations: [CreateGameComponent],
providers: [RequestService, SessionService, AdminService],
})
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(CreateGameComponent);
component = fixture.componentInstance;
component.isShown = false;
fixture.detectChanges();
});
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should check if toggleDropdownwas called', fakeAsync(() => {
spyOn(component, 'toggleDropdown');
let button =
fixture.debugElement.nativeElement.querySelector('#game-category');
button.click();
tick();
fixture.detectChanges();
expect(component.toggleDropdown).toHaveBeenCalled();
expect(component.isShown).toBe(true, 'isShown has not changed');
}));
})
触发点击事件isShown
属性后不会改变它的值。任何帮助表示赞赏。谢谢!
uj5u.com热心网友回复:
当您这样做时spyOn(component, 'toggleDropdown');
,它会模拟该方法,其内容变为空,并且不再执行。您必须添加spyOn(component, 'toggleDropdown').and.callThrough()
,因此实际上呼叫了该方法。
0 评论