'Set the toggle to check by clicking on the label is failed
I create a slideToggle in Angular (latest version). Unfortunately, I got a failure from a unit test that set the toggle to check by clicking on the label.
FYI, I already set the for attribute to the id of the element.
Here are the component and spec files:
Component
@Component({
template: `<label [attr.for]="id"
><input
#input
type="checkbox"
[ngClass]="{'checked': checked}"
[checked]="checked"
[attr.id]="id"
[name]="name"
[disabled]="disabled"
[required]="required"
[attr.aria-checked]="checked"
(change)="onChangeEvent($event)"
(click)="onInputClick($event)"
/><span>{{ placeholder }}</span></label
>`,
})
class TestToggleComponent {
@Input() public placeholder = '';
@Input() public name = '';
@Input() public checked = false;
@Input() public disabled = false;
@Input() public required = false;
@HostBinding() public id = `toggle-input-${TestToggleComponent.nextId}`;
@ViewChild('input') inputElement?: ElementRef<HTMLInputElement>;
private static get nextId(): string {
return uid();
}
public onChangeEvent(event: Event): void {
event.stopPropagation();
if (this.inputElement && !this.disabled) {
this.checked = !this.checked;
this.inputElement.nativeElement.checked = this.checked;
return;
}
this.checked = this.inputElement?.nativeElement.checked ?? this.checked;
}
public onInputClick(event: Event): void {
event.stopPropagation();
}
}
Spec file
describe('TestToggleComponent', () => {
let fixture: ComponentFixture<TestToggleComponent>;
let component: TestToggleComponent;
let toggleEl: DebugElement;
let labelEl: DebugElement;
let spanEl: DebugElement;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [TestToggleComponent],
providers: [{provide: ComponentFixtureAutoDetect, useValue: true}],
}).compileComponents();
fixture = TestBed.createComponent(TestToggleComponent);
component = fixture.componentInstance;
toggleEl = fixture.debugElement.query(By.css('input'));
labelEl = fixture.debugElement.query(By.css('label'));
spanEl = fixture.debugElement.query(By.css('span'));
fixture.detectChanges();
});
it('should set the toggle to checked on click', fakeAsync(() => {
const toggle = toggleEl.nativeElement;
const label = labelEl.nativeElement;
expect(toggle.checked).toBe(false);
expect(toggle.getAttribute('aria-checked')).toBe('false');
expect(toggle.classList).not.toContain('checked');
const spyOnChangeEvent = jest.spyOn(component, 'onChangeEvent');
label.click();
fixture.detectChanges();
flush();
expect(spyOnChangeEvent).toBeCalled();
expect(toggle.classList).toContain('checked');
expect(toggle.checked).toBe(true);
expect(toggle.getAttribute('aria-checked')).toBe('true');
}));
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
