![](/img/trans.png)
[英]Angular 6 Error "NullInjectorError: No provider for Router!"
[英]Angular Test Error - NullInjectorError: No provider for TrimInputDirective
我創建了一個Angular Directive,它使用CSS選擇器自動修剪我的應用程序中的輸入,它看起來像......
import { Directive, HostListener, forwardRef } from '@angular/core';
import { DefaultValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
export const TRIM_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => TrimInputDirective),
multi: true
};
/**
* The trim accessor for writing trimmed value and listening to changes that is
* used by the {@link NgModel}, {@link FormControlDirective}, and
* {@link FormControlName} directives.
*/
/* tslint:disable */
@Directive({
selector: `
input
:not([type=checkbox])
:not([type=radio])
:not([type=password])
:not([readonly])
:not(.ng-trim-ignore)
[formControlName],
input
:not([type=checkbox])
:not([type=radio])
:not([type=password])
:not([readonly])
:not(.ng-trim-ignore)
[formControl],
input
:not([type=checkbox])
:not([type=radio])
:not([type=password])
:not([readonly])
:not(.ng-trim-ignore)
[ngModel],
textarea
:not([readonly])
:not(.ng-trim-ignore)
[formControlName],
textarea
:not([readonly])
:not(.ng-trim-ignore)
[formControl],
textarea
:not([readonly])
:not(.ng-trim-ignore)[ngModel],
:not([readonly])
:not(.ng-trim-ignore)
[ngDefaultControl]'
`,
providers: [ TRIM_VALUE_ACCESSOR ]
})
/* tslint:enable */
export class TrimInputDirective extends DefaultValueAccessor {
protected _onTouched: any;
/**
* ngOnChange - Lifecycle hook that is called when any data-bound property of a directive changes.
* @param {string} val - trim value onChange.
*/
@HostListener('input', ['$event.target.value'])
public ngOnChange = (val: string) => {
this.onChange(val.trim());
}
/**
* applyTrim - trims the passed value
* @param {string} val - passed value.
*/
@HostListener('blur', ['$event.target.value'])
public applyTrim(val: string) {
this.writeValue(val.trim());
this._onTouched();
}
/**
* writeValue - trims the passed value
* @param {any} value - passed value.
*/
public writeValue(value: any): void {
if (typeof value === 'string') {
value = value.trim();
}
super.writeValue(value);
}
/**
* registerOnTouched Registers a callback function that should be called when the control receives a blur event.
* @param {function} fn - The user information.
*/
public registerOnTouched(fn: any): void {
this._onTouched = fn;
}
}
現在做一個好的開發人員我必須對一些單元測試...所以我開始把文件放在一起,就在這里
import {Component} from '@angular/core';
import {async, ComponentFixture, TestBed} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {TrimInputDirective} from './trim-input.directive';
import {expect} from 'chai';
@Component({
selector: 'my-directive-test-component',
template: ''
})
class TestComponent {
}
describe('Trim Directive', () => {
let fixture: ComponentFixture<TestComponent>;
let inputDebugElement: any;
let directive: TrimInputDirective;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
TestComponent,
TrimInputDirective
],
providers: []
}).overrideComponent(TestComponent, {
set: {
template: '<input type="text">'
}
}).compileComponents().then(() => {
fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
inputDebugElement = fixture.debugElement.query(By.css('input'));
directive = inputDebugElement.injector.get(TrimInputDirective);
});
}));
it('should trim the input', () => {
directive.ngOnChange(' 1234.56 ')
expect('1234.56').to.be('1234.56'); // I know this isn't the correct test... I will amend this
});
});
現在我希望運行我的測試只是為了確保spec文件中的設置是正確的,但是我收到以下錯誤:
HeadlessChrome 0.0.0(Mac OS X 10.12.6)修剪指令“在每個”掛鈎之前“應修剪輸入”FAILED未捕獲(在承諾中):錯誤:StaticInjectorError(DynamicTestModule)[TrimInputDirective]:
StaticInjectorError(Platform:core)[TrimInputDirective]:NullInjectorError:沒有TrimInputDirective的提供者! 錯誤:StaticInjectorError(DynamicTestModule)[TrimInputDirective]:
我不明白為什么我得到這個錯誤,為什么我必須提供指令? 我不認為這是必要的,如果我必須提供我提供的內容嗎? 提供實際指令不起作用/解決錯誤? 我很迷茫。 如果有人能告訴我如何解決問題或為什么我得到它,我將非常感激。
請注意,這是一個傳統的Angular應用程序,是在AngularCLI可用之前構建的。 所以它有點不正統(例如它不使用Jasmin)。
1)您不需要提供您的指令,您只需要在TestingModule
聲明它。 然后,它將在具有相應選擇器的模板中使用。
2)您的選擇器與輸入中使用的選擇器不對應。 如果要將formControlName
應用於某些類型的所有輸入或更改測試,請將其刪除。
input
:not([type=checkbox])
:not([type=radio])
:not([type=password])
:not([readonly])
:not(.ng-trim-ignore)
[formControlName],
^^^^^^^^^^^^^^^^^^
3)指令在某些事件中被觸發。 您需要模擬這些事件才能看到效果。 看看這個簡化的例子。 ( Stackblitz )
@Directive({
selector: `
input
:not([type=checkbox])
:not([type=radio])
:not([type=password])
:not([readonly])
:not(.ng-trim-ignore)
`
})
export class TrimInputDirective {
constructor(private el: ElementRef) { }
@HostListener('blur') onLeave() {
if (this.el.nativeElement.value)
this.el.nativeElement.value = this.el.nativeElement.value.trim();
}
}
而且測試:
describe('Trim Directive', () => {
let fixture: ComponentFixture<TestComponent>;
let inputDebugElement: any;
let directive: TrimInputDirective;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
TestComponent,
TrimInputDirective
],
imports: [FormsModule],
providers: []
}).overrideComponent(TestComponent, {
set: {
template: '<input type="text">'
}
}).compileComponents().then(() => {
fixture = TestBed.createComponent(TestComponent);
inputDebugElement = fixture.debugElement.query(By.css('input')).nativeElement;
^^^^^^^^^^^^
});
}));
it('should trim the input', () => {
inputDebugElement.value = ' 1234.56 ';
inputDebugElement.dispatchEvent(new Event('blur'));
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
fixture.detectChanges();
expect(inputDebugElement.value).toBe('1234.56');
});
});
您必須在TestComponent
提供類似這樣的指令
@Component({
selector: 'my-directive-test-component',
template: '',
providers: [ TrimInputDirective ]
})
class TestComponent {
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.