Nei*_*ens 2 angular angular-test
如何模拟一个ControlContainer实例,以便测试我的组件?
我有一个将a ControlContainer注入构造函数的子组件,因此其用法是
<acr-score-card formGroupName="score"></acr-score-card>
Run Code Online (Sandbox Code Playgroud)
组件本身是
@Component({
selector: 'acr-score-card',
templateUrl: './score-card.component.html',
styleUrls: ['./score-card.component.scss']
})
export class ScoreCardComponent implements OnInit {
...
form: FormGroup;
constructor(private ngControl: ControlContainer) { }
ngOnInit() {
this.form = <FormGroup>this.ngControl.control;
}
...
}
Run Code Online (Sandbox Code Playgroud)
当我在浏览器中运行时,一切正常,但由于不确定如何模拟ControlContainer实例以设置提供程序,因此无法使单元测试正常工作,这是我的spec文件的内容:
describe('ScoreCardComponent', () => {
let component: ScoreCardComponent;
let fixture: ComponentFixture<ScoreCardComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [TestingModule],
declarations: [ScoreCardComponent],
providers: [/** what goes here to mock the ControlContainer */]
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ScoreCardComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
Run Code Online (Sandbox Code Playgroud)
因此,要重复这个问题,我如何模拟一个ControlContainer实例,以便可以测试我的组件?
感谢@KiraAG的评论,并能够确定提供的链接中需要什么,因此在此处发布答案,以防其他人遇到此问题
因此,在您的测试,你需要provide的ControlContainer情况下你的测试模块,这基本上将是A FormGroupDirective还是FormControlDirective取决于你希望传递给您的组件是什么。
例如,在测试文件中,创建FormGroup代表您正在使用的表单部分的
const fg: FormGroup = new FormGroup({
'answer': new FormControl(''),
...
});
Run Code Online (Sandbox Code Playgroud)
接下来创建一个FormGroupDirective并将form属性设置为FormGroup上面创建的
const fgd: FormGroupDirective = new FormGroupDirective([], []);
fgd.form = fg;
Run Code Online (Sandbox Code Playgroud)
现在,在测试模块设置中,您可以提供 ControlContainer
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [TestingModule],
declarations: [ScoreCardComponent],
providers: [
{ provide: ControlContainer, useValue: fgd }
]
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();
}));
Run Code Online (Sandbox Code Playgroud)
就是这样,构造函数注入就可以了。
小智 5
我使用了尼尔史蒂文斯的答案。
但我有
viewProviders: [{provide: ControlContainer, useExisting: FormGroupDirective}],
Run Code Online (Sandbox Code Playgroud)
在组件中。
所以在测试中我必须使用
providers: [{provide: FormGroupDirective, useValue: fgd}],
Run Code Online (Sandbox Code Playgroud)
也许这会对某人有所帮助。
| 归档时间: |
|
| 查看次数: |
806 次 |
| 最近记录: |