我正在尝试在Angular中测试组件方法。它使用反应形式。
测试如下。
fit('should try to login with credentials when the form is valid', () => {
const form = fixture.componentInstance.signupForm;
fixture.componentInstance.ngOnInit();
const email = 'test@joveo.com',
password = 'test',
rememberMe = false,
redirect = '';
form.controls['email'].setValue(email);
form.controls['password'].setValue(password);
form.controls['rememberMe'].setValue(rememberMe);
expect(form.valid).toBe(true);
const action = new AuthActions.Login({
email,
password,
rememberMe,
redirect
});
console.log(form, form.valid, form.value);
fixture.componentInstance.login();
expect(store.dispatch).toHaveBeenCalledWith(action);
});
组件方法login
定义如下。
login() {
console.log(this.signupForm, this.signupForm.valid, this.signupForm.value);
if (!this.signupForm.valid) {
return;
}
const { email, password, rememberMe } = this.signupForm.value;
const redirect = this.route.snapshot.queryParams['redirect'] || '';
this.store.dispatch(new Login({ email, password, rememberMe, redirect }));
}
可见,我在测试和方法中都有console.log
语句。
由于fixture.componentInstance
在测试中调用了login方法,我希望this
成为componentInstance,因此应该是signupForm
。
但他们表现出不同的结果。在方法内部,表单控件的值为null。
我在这里做的事真的很蠢吗?
我疯狂地猜测,当我使用像form.controls['email'].setValue('test@test.joveo.com')
之类的东西设置值时,它并没有真正改变实际的fixture.componentInstance.signupForm
。
因此,在我的所有setValue
来电之后,我将form
重新分配给fixture.componentInstance.signupForm
并且它有效。
这完全破坏了我所知道的JS引用如何工作!
答案 0 :(得分:0)
我通过在ngOnInit()
const form = fixture.componentInstance.signupForm;
来修复此问题
由于在ngOnInit
我将this.signupForm
分配给new FormGroup({...})
,引用正在发生变化,而form
变量并未发现它。