У меня есть следующая простая директива автофокуса:
@Directive({
selector: '[appAutoFocus]',
})
export class AutofocusDirective implements AfterContentInit {
@Input() public appAutoFocus: boolean;
public constructor(private el: ElementRef) { }
public ngAfterContentInit() {
if (this.appAutoFocus) {
setTimeout(() => {
this.el.nativeElement.focus();
}, 300);
}
}
}
Я сейчас пытаюсь написать несколько простых модульных тестов, но 2 из 3 тестов не пройдены.
@Component({
template: '<input type="text" [appAutoFocus]="true" />'
})
class TestComponent {
constructor() { }
}
fdescribe('AutoFocusDirective', () => {
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
let inputEl: DebugElement;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
TestComponent,
AutofocusDirective
]
});
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
inputEl = fixture.debugElement.query(By.css('input'));
spyOn(inputEl.nativeElement, 'focus');
fixture.detectChanges();
});
it('should create an instance', () => {
expect(component).toBeTruthy();
});
it('should call the focus event', fakeAsync(() => {
tick(400);
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(inputEl.nativeElement.focus).toHaveBeenCalled();
});
}));
it('should autofocus the input control', () => {
const debugEl: DebugElement = fixture.debugElement;
expect(debugEl.query(By.css('input:focus'))).not.toBe(null);
});
«Следует вызвать событие фокуса» завершается неудачей с Spec 'AutoFocusDirective should call the focus event' has no expectations.
«Если автофокусировка управления вводом» завершается с Expected null not to be null