如何对 ngControl 装饰有 @Self 的反应式组件进行单元测试 [英] How to unit test a reactive component where ngControl is decorated with @Self
问题描述
我通过注入 NgControl 编写了一个反应式组件,并使用 @Self 装饰器进行装饰.我的问题与此类组件的单元测试有关.请看下面的代码:
I've written a reactive component by injecting the NgControl and which is decorated using the @Self decorator. My problem is related to unit testing of such component. Please look at the code below:
免责声明:我已经快速复制了代码并进行了一些内联更改.所以,这可能不是一个编译器满意的代码.
Disclaimer: I've quickly copied the code and made some inline changes. So, this might not be a compiler happy code.
我的反应式组件:
@Component({
selector: 'text-input',
templateUrl: '<input type="text" class="native_input" />'
})
class TextInput implements ControlValueAccessor {
protected constructor(@Self() public controlDir: NgControl) {
this.controlDir.valueAccessor = this;
}
// ...followed by other ControlValueAccessor methods
}
单元测试:
describe('TextInput -', () => {
let fixture: ComponentFixture<TextInputHost>;
let textInput: TextInput;
let inputElement: HTMLInputElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
TextInput, TextInputHost
],
imports: [
FormsModule, ReactiveFormsModule
]
});
}));
beforeEach(fakeAsync(() => {
fixture = getTestBed().createComponent(TextInputHost);
textInput = fixture.componentInstance.textInputComponent;
textInput.writeValue('TestValue');
inputElement = fixture.debugElement
.query(By.css('native_input')).nativeElement;
fixture.detectChanges();
tick();
}));
it('Should have the initial value applied.', () => {
expect(inputElement.value).toBe('TestValue');
});
});
// Host component
@Component({
template: `
<form [formGroup]="pageForm">
<text-input formControlName="testInput">
</text-input>
</form>`
})
class TextInputHost {
@ViewChild(TextInput)
public textInputComponent: TextInput;
public pageForm: FormGroup = new FormGroup({
testInput: new FormControl('Initial Value')
});
}
每当我尝试运行上述单元测试时.它失败并出现以下错误:<代码>模板解析错误:无 NgControl 提供程序 --><文本输入>....</文本输入>
Whenever I try to run the above unit test. It fails with the following error:
Template parse errors: No provider for NgControl --> <text-input>....</text-input>
所以我正在寻找一种方法来成功运行上述单元测试.什么,我正在寻找一种将 NgControl 注入 TextInput
组件的方法.
So I'm looking for a way to successfully run the above unit test. What, I'm looking for is a way to inject the NgControl to the TextInput
component.
推荐答案
如果有人偶然发现这个问题,我使用 TestBed 类的 overrideComponent() 方法解决了它.
If anybody stumbles upon this question, I solved it using the overrideComponent() method of the TestBed class.
注意:如果您认为您还有其他答案,请随时回答这个问题.
注入 NgControl:
To inject the NgControl:
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
TextInput, TextInputHost
],
imports: [
FormsModule, ReactiveFormsModule
]
})
.overrideComponent(TextInput, {
set: {
providers: [
{
provide: NgControl,
useValue: new FormControlDirective([], [], null, null)
}
]
}
});
}));
这篇关于如何对 ngControl 装饰有 @Self 的反应式组件进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!