我正在使用jest.js
我的角度应用程序进行测试。这是我在 html 中使用的指令:
<textarea errorHighlighter formControlName="Url" name="Url" cols="50" rows="5"
placeholder="Enter Page URL" (ngModelChange)="pageUrlChanges($event)"></textarea>
这是我的directive.ts 文件:
import { Directive, ElementRef, SimpleChanges, HostListener, Renderer2 } from '@angular/core';
import { NgControl } from '@angular/forms';
@Directive({
selector: '[errorHighlighter]'
})
export class ErrorHighlighterDirective {
constructor(private el: ElementRef, private control: NgControl, private renderer: Renderer2) { }
@HostListener('input') oninput() {
if (this.el.nativeElement && this.control) {
if (this.control.control.status === 'INVALID') {
this.renderer.addClass(this.el.nativeElement, 'has-err');
} else {
this.renderer.removeClass(this.el.nativeElement, 'has-err');
}
}
}
}
这是为了显示输入字段周围的错误边框。我正在尝试像这样测试:
import { ErrorHighlighterDirective } from './error-highlighter.directive';
import { Directive, ElementRef, SimpleChanges, HostListener, Renderer2, Component, DebugElement } from '@angular/core';
import { NgControl, FormGroup, FormsModule, FormControl, ReactiveFormsModule } from '@angular/forms';
import { TestBed, ComponentFixture } from '@angular/core/testing';
@Component({
template: `<input errorHighlighter formControlName="Url" type="text">`
})
class TestHighlighterComponent { }
describe('ErrorHighlighterDirective', () => {
let component: TestHighlighterComponent;
let fixture: ComponentFixture<TestHighlighterComponent>;
let inputEl: DebugElement;
const fg: FormGroup = new FormGroup({
'Url': new FormControl('')
});
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [TestHighlighterComponent, ErrorHighlighterDirective],
imports: [FormsModule, ReactiveFormsModule],
providers: [
{ provide: NgControl, useValue: fg }
]
});
fixture = TestBed.createComponent(TestHighlighterComponent);
component = fixture.componentInstance;
inputEl = fixture.debugElement.query(By.css('input'));
});
it('should create an instance', () => {
const directive = new ErrorHighlighterDirective(inputEl, fg, Renderer2);
expect(directive).toBeTruthy();
});
});
但是测试没有成功。出现如下错误:
● Test suite failed to run
TypeScript diagnostics (customize using `[jest-config].globals.ts-jest.diagnostics` option):
src/app/directives/error-highlighter.directive.spec.ts:33:46 - error TS2304: Cannot find name 'By'.
33 inputEl = fixture.debugElement.query(By.css('input'));
~~
src/app/directives/error-highlighter.directive.spec.ts:38:66 - error TS2345: Argument of type 'FormGroup' is not assignable to parameter of type 'NgControl'.
Type 'FormGroup' is missing the following properties from type 'NgControl': name, valueAccessor, viewToModelUpdate, control, path
38 const directive = new ErrorHighlighterDirective(inputEl, fg, Renderer2);
任何人帮助我理解和解决这些问题?我对角度测试也不太熟悉 jest.js。