【发布时间】:2020-02-19 17:05:17
【问题描述】:
我有以下简单的自动对焦指令:
@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);
}
}
}
我现在正在尝试编写一些简单的单元测试,但是 3 个测试中有 2 个失败了。
@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
【问题讨论】: