javascript - 角度测试错误 - NullInjectorError:没有 TrimInputDirective 的提供者
问题描述
我创建了一个 Angular 指令,它使用 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
});
});
现在我希望运行我的测试以确保规范文件中的设置正确,但我收到以下错误:
HeadlessChrome 0.0.0 (Mac OS X 10.12.6) Trim Directive "before each" hook for "should trim the input" FAILED Uncaught (in promise): Error: StaticInjectorError(DynamicTestModule)[TrimInputDirective]:
StaticInjectorError(Platform: core)[ TrimInputDirective]:NullInjectorError:没有 TrimInputDirective 的提供者!错误:StaticInjectorError(DynamicTestModule)[TrimInputDirective]:
我不明白为什么会出现此错误,为什么必须提供指令?我不认为这是必要的,如果我必须提供我应该提供什么?提供实际指令不起作用/解决错误?我很困扰。如果有人能告诉我如何解决这个问题或我为什么得到它,我将不胜感激。
请注意,这是一个遗留的 Angular 应用程序,是在 AngularCLI 可用之前构建的。所以它有点不正统(例如它没有使用 Jasmin)。
解决方案
你必须在你的TestComponent
类似这样的东西中提供指令
@Component({
selector: 'my-directive-test-component',
template: '',
providers: [ TrimInputDirective ]
})
class TestComponent {
}
推荐阅读
- android - UnhandleException: PlatformException(error, PluginRegistrantCallback is not set., null, java.lang.RuntimeException:PluginRegistrantCallback is not set
- firebase - Firebase Flutter:查询接收 null 但重新加载模拟器时工作正常
- python - 我在 monjaro linux 上找不到 python 模块
- go - Cookie 未在前端设置,即使它存在于网络选项卡中
- javascript - CSS网格没有变成带有媒体查询的5列
- loops - 如何使用循环或其他函数计算具有不同组条件的多列的统计信息(中位数、标准差、最大值、最小值)
- python - 如何通过从 mongodb 到 csv 文件的子类别匹配技能
- android - 我正在尝试在 Jetpack compose 中使用 Tab Row 我增加了指示高度,现在我的文本隐藏在它后面如何解决它?
- amazon-web-services - 如何在 AWS 上向 Flutter 应用程序发送推送通知
- javascript - 如何计算一个新日期,距所选日期 3 天,然后将新日期与所选日期进行比较