gpt4 book ai didi

Angular 单元测试 - 响应式表单值未更新

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

我是 Angular 单元测试的新手。
测试场景:html中的表单 View 值等于组件表单值。
电子邮件值由共享值检索并在组件注册表中使用。我可以使用响应式(Reactive)表单从组件中检索电子邮件值,但是当尝试通过 native 元素访问时,它给出了空值。
下面是component.ts

ngOnit(public serviceEmail) {
this.assignEmailAvailable();
this.createRegistration();

}
assignEmailAvailable() {
if(service.email){
this.email = serviceEmail.email;
}
}
createRegistration() {
this.registerForm = new FormGroup({
email:new FormControl({value:this.email})
})
}

在 component.spec.ts 中,我将调用此函数并检查两个值是否相同。
组件.spec.ts
 beforeEach(() => {
fixture = TestBed.createComponent(RegisterComponent);
component = fixture.componentInstance;
service = TestBed.get(serviceEmail);
});
it('Registration Form Creation', fakeAsync(() => {
service.email = "dsf@gmail.com";

fixture.detectChanges();

component.assignEmailAvailable();
component.createRegisterForm();

fixture.detectChanges();
fixture.whenStable().then(() => {
const email = fixture.debugElement.query(By.css('input[id="email"]')).nativeElement;
//The value is empty even after creating the form using the component function
expect(email.value).toBe(component.emailValue);
});
//THis returns me the value set
expect(component.registerForm.get('email').value).toBe(component.emailValue);
}));

最佳答案

我只是花了大约 2 个小时试图找出这个问题。根据我的经验,您需要解决 beforeEach() 函数中的一些问题。首先,您需要将 ReactiveFormsModule 导入您的 TestBed,以便 Change Detection 正确执行所有操作。其次,您需要在 beforeEach() 调用中手动运行 ngOnInit() 和 fixture.detectChanges() 来设置表单。请参阅下面的 beforeEach() 函数。我还包含了其他与此问题相关的代码。
组件模板:


<form [formGroup]='emailForm' (ngSubmit)='handleSubmit()'>
<div class='form-group'>
<label for='email'>Email address</label>
<input type='email' class='form-control' id='email' placeholder='Enter email'
formControlName='email'>

组件 TS:
  constructor(
private apiService: ApiService,
private fb: FormBuilder,
private router: Router
) { }

ngOnInit() {
this.initializeForm();
}

initializeForm(): void {
this.formSubmitted = false;
this.serverProcessing = false;
this.emailForm = this.fb.group({
email: ['', Validators.compose([Validators.required, Validators.email])]
});
}

get email() {return this.emailForm.get('email');}
Spec TS 中的两个 beforeEach() 调用:
beforeEach(
async(() => {

apiServiceSpy = jasmine.createSpyObj('ApiService', ['sendResetPasswordEmail']);
routerSpy = jasmine.createSpyObj('Router', ['navigateByUrl']);

TestBed.configureTestingModule({
declarations: [ SendPasswordResetEmailComponent ],

// Need to import this if we're messing with Reactive Form inputs!!
imports: [ReactiveFormsModule],

providers: [
{provide: ApiService, useValue: apiServiceSpy},
{provide: Router, useValue: routerSpy},
{provide: FormBuilder},
]
})
.compileComponents();
})
);

beforeEach(() => {
fixture = TestBed.createComponent(SendPasswordResetEmailComponent);
component = fixture.componentInstance;

// ngOnInit() doesn't get called automatically, so we have to do it ourselves
component.ngOnInit();

// Telling the fixture to detect changes is really important to correctly bind data
// Do this after calling ngOnInit() so changes propagate to the template
fixture.detectChanges();
});
sample 测试规范:
it('should have an error for no username', () => {
const componentElement: HTMLElement = fixture.nativeElement;
const emailInput: HTMLInputElement = componentElement.querySelector('input');
emailInput.value = '@gmail.com';
emailInput.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(component.email.errors.email).toBeTruthy('@gmail.com valid');
});

it('should have no error if the email is valid', () => {
const componentElement: HTMLElement = fixture.nativeElement;
const emailInput: HTMLInputElement = componentElement.querySelector('input');
emailInput.value = 'joe@test.go';
emailInput.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(component.email.errors).toBeFalsy('joe@test.go invalid');
});

关于Angular 单元测试 - 响应式表单值未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59638229/

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