gpt4 book ai didi

angular - 如何在 Angular 中测试 form.valueChanges?

转载 作者:行者123 更新时间:2023-12-04 01:23:50 25 4
gpt4 key购买 nike

如何正确地进行单元测试(Karma、Jasmine),即 valueChanges dispatch FormUpdated行动?

beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [...],
providers: [
{ provide: Store, useValue: MOCK_STORE },
],
declarations: [FormComponent],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();
}));

beforeEach(() => {
fixture = TestBed.createComponent(FormComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});

export class FormComponent implements OnInit {
searchForm: FormGroup;

constructor(private readonly fb: FormBuilder, private readonly store: Store<AppState>) {
}

ngOnInit(): void {
this.searchForm = this.fb.group({});
this.searchForm.valueChanges.subscribe(value => this.store.dispatch(new FormUpdated(value)));
}
}

我试过这样的事情:

it('should dispatch action for valueChanges', () => {
const spy = spyOn(component['store'], 'dispatch');
spyOn(component.searchForm, 'valueChanges').and.returnValue(of({}));

expect(spy).toHaveBeenCalledTimes(1);
});

但这不起作用 - spy 没有被调用。

[Edit1] - 基于评论和回答:

问题在于测试的异步性。 ngOnInit的部分内容电话 setTimeout(() => this.searchForm.get('field').updateValueAndValidity();) ) 导致排放到 this.searchForm.valueChanges()所以 this.store.dispatch 实际上被调用,但在 之后 expect(spy).toHaveBeenCalledTimes(1) .

我试图添加 fakeAsync() , tick()flushMicrotasks()但结果相同。

it('should dispatch action for valueChanges', () => {
const spy = spyOn(component['store'], 'dispatch');
spyOn(component.searchForm, 'valueChanges').and.returnValue(of({}));

tick();
flushMicrotasks();

expect(spy).toHaveBeenCalledTimes(1);
});

最佳答案

您想在没有输入的表单上测试更改。
也许试试这个:

this.searchForm = this.fb.group({description: ['your_input']});

.
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [...],
providers: [
{ provide: Store, useValue: MOCK_STORE },
],
declarations: [FormComponent],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();
}));

beforeEach(() => {
fixture = TestBed.createComponent(FormComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});

it('should dispatch action for valueChanges', () => {
const spy = spyOn(TestBed.get(Store<AppState>), 'dispatch')
component.searchForm.controls['your_input'].setValue('test') // This will trigger change
expect(spy).toHaveBeenCalledTimes(1);
});

关于angular - 如何在 Angular 中测试 form.valueChanges?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52856875/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com