Unit test in Angular - property value not updating
I have a simple function that shows and hides a dropdown menu on click events.This is HTML code
<div (click)="toggleDropdown()" id="game-category">Show/Hide menu</div>
<div >
<app-category *ngIf="isShown" [filtersList]="categories">
</app-category>
</div>
This function sets the opposite value to the component's property value.
isShown=false;
toggleDropdown(): void {
this.isShown=!this.isShown;
}
Everything works fine, but when I run the quiz I get an error.This is the quiz code:
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');
}));
})
Trigger click eventisShown
attribute does not change its value.Any help is appreciated.Thanks!
uj5u.com enthusiastic netizens replied:
When you do thisspyOn(component, ' toggleDropdown');
, which emulates the method, its content becomes empty and no longer implement.you must add spyOn(component, 'toggleDropdown').and.callThrough()
, so that method is actually called.
0 Comments