在单元测试中模拟 NgControl 以访问验证器 [英] Mock NgControl in unit-test to access validators

查看:23
本文介绍了在单元测试中模拟 NgControl 以访问验证器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在对通过 NgControl 设置验证器的指令进行单元测试时遇到问题.

I'm having trouble unit-testing a directive that sets validators via NgControl.

这是我在指令中所做的:

Here's what I'm doing inside my directive:

constructor(private control: NgControl) {
}

ngOnInit() {
    const ctrl = this.control.control;
    if (ctrl) {
        // this condition never passes here when run inside the test

        ctrl.setValidators([/* my validators*/]);
    }
}

在我的测试中,我尝试了多种方法来注入 NgControl,如下所示:

In my test, I tried a number of ways to inject that NgControl, like this one:

{ provide: NgControl, useValue: new FormControl() }

但没有任何效果.在测试中,指令中的 ctrl 始终为 null.与此同时,该指令通常可以完美运行.

But nothing works. Inside the test, ctrl within the directive is always null. In the meantime, normally the directive works perfectly.

我不知道该往哪里看.非常感谢任何帮助!

I no longer know where to look. Any help is much appreciated!

我使用的是 Angular v12.02

I'm using Angular v12.02

推荐答案

借助 这篇文章,稍作修改,我能够让它工作......

With this help of this post, modified somewhat, I was able to get it to work...

加了两块...

const NG_CONTROL_PROVIDER = {
    provide: NgControl,
    useClass: class extends NgControl {
        control = new FormControl();

        viewToModelUpdate() {
        }
    }
};

并在编译前加上以下 overrideDirective 片段:

And plus the following overrideDirective piece before compilation:

TestBed.configureTestingModule({
    declarations: [ValidationConfigDirective, HostComponent]
})
    .overrideDirective(ValidationConfigDirective, {
        add: { providers: [NG_CONTROL_PROVIDER] }
    })
    .compileComponents();

这篇关于在单元测试中模拟 NgControl 以访问验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆