这是我的指令规范文件。我正在使用角度6。
import { Component, DebugElement, NO_ERRORS_SCHEMA } from '@angular/core';
import { TestBed, ComponentFixture, async } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { KeyboardInputDirective } from './keyboard-input.directive';
@Component({
selector: 'kiosk-app-test-component',
template: `<input type="text" name="wu-input" class="wu-input" id="standard" [kioskAppKeyboardInput]="'true'">`
})
class TestStubComponent { }
describe('Directive: KeyboardInputDirective', () => {
let component: TestStubComponent;
let fixture: ComponentFixture<TestStubComponent>;
let directiveEl: DebugElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [TestStubComponent, KeyboardInputDirective],
schemas: [NO_ERRORS_SCHEMA]
});
TestBed.compileComponents().then(() => {
fixture = TestBed.createComponent(TestStubComponent);
component = fixture.componentInstance;
directiveEl = fixture.debugElement.query(By.directive(KeyboardInputDirective));
});
}));
fit('should create an instance', () => {
fixture.detectChanges();
expect(directiveEl).not.toBeNull();
});
});
我不断遇到错误。
TypeError: Cannot read property 'query' of null
如果我使用控制台fixture.debugElement
值,则始终为null。非常感谢您的帮助。
可能您需要按如下方式在describe中移动fixture.detectChanges();。
describe('Directive: KeyboardInputDirective', () => {
let component: TestStubComponent;
let fixture: ComponentFixture<TestStubComponent>;
let directiveEl: DebugElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [TestStubComponent, KeyboardInputDirective],
schemas: [NO_ERRORS_SCHEMA]
});
TestBed.compileComponents().then(() => {
fixture = TestBed.createComponent(TestStubComponent);
component = fixture.componentInstance;
fixture.detectChanges();
directiveEl = fixture.debugElement.query(By.directive(KeyboardInputDirective));
});
}));
希望这会有所帮助,如果您遇到问题,请告诉我。
TestBed.compileComponents
,但是在查询fixture.detectChanges
元素之前需要调用HTML
。您可以查询input
元素并在测试中与之交互,以查看指令是否正常工作。不知道您的指令真正做什么,显然需要对以下测试进行调整,以使其对您有用。
describe('Directive: KeyboardInputDirective', () => {
let component: TestStubComponent;
let fixture: ComponentFixture<TestStubComponent>;
let inputElement: HTMLInputElement;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [TestStubComponent, KeyboardInputDirective]
});
fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
component = fixture.componentInstance;
inputElement = <HTMLInputElement>fixture.debugElement.nativeElement.querySelector('INPUT');
});
...
it('#keydown should ...', fakeAsync(() => {
// given
inputElement.value = 'abc';
const event = new KeyboardEvent('keydown', { key: '' });
// when
inputElement.dispatchEvent(event);
tick();
// then
expect(inputElement.setSelectionRange).toHaveBeenCalledWith(0, 3);
}));