Jest.js 在调用ngAfterContentInit钩子之前模拟类成员

xytpbqjk  于 12个月前  发布在  Jest
关注(0)|答案(1)|浏览(111)

我有一个组件,它可以像下面这样查询它的内容子级

@ContentChild(InputControlDirective, { read: ElementRef })
public inputControl: ElementRef;

我有ngAfterContentInit钩子,它检查inputControl是否有值,否则抛出一个自定义错误

public ngAfterContentInit(): void {
        if (!this.inputControl) {
                throw new Error(
                    'Provide a InputControlDirective for the field used with the form-input component like  <input inputControl>'
                );
            }
}

如何在下面的单元测试的ngAfterContentInit钩子之前模拟inputControl

describe('FormInputComponent', () => {
    let component: FormInputComponent;
    let fixture: ComponentFixture<FormInputComponent>;

    beforeEach(async () => {
        await TestBed.configureTestingModule({
            imports: [FormInputComponent],
        }).compileComponents();

        fixture = TestBed.createComponent(FormInputComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should create', () => {
        expect(component).toBeTruthy();
    });
    });

组件实现是不是使单元测试成为一个挑战?

ktecyv1j

ktecyv1j1#

经过一些阅读,我能够弄清楚为什么我嘲笑班级成员的尝试没有奏效。

之前

beforeEach(async () => {
        await TestBed.configureTestingModule({
            imports: [FormInputComponent],
        }).compileComponents();

        fixture = TestBed.createComponent(FormInputComponent);

        component = fixture.componentInstance;

        component.control = {} as FormControlName;
        component.inputControl = {} as ElementRef;

        fixture.detectChanges();
    });

之后

beforeEach(async () => {
        await TestBed.configureTestingModule({
            imports: [FormInputComponent],
        }).compileComponents();

        fixture = TestBed.createComponent(FormInputComponent);

        component = fixture.componentInstance;

        component.control = {} as FormControlName;
        component.inputControl = {} as ElementRef;

        setTimeout(() => {
            fixture.detectChanges();
        });
    });

注意setTimeout
关于Angular documentation
延迟的变化检测是有意的和有用的。在Angular启动数据绑定和调用生命周期钩子之前,它为测试人员提供了检查和更改组件状态的机会。

相关问题