[英]Angular2 FormBuilder unit testing
I have two question in regards to mocking Formbuilder in Angular2. 关于在Angular2中模拟Formbuilder,我有两个问题。
1) How do I mock formBuilder in a spec? 1)如何在规范中模拟formBuilder? Are there any given mocks that we can use?
我们可以使用任何给定的模拟吗? I would like to for instance, update the values of a form in my spec, and then test to see if the form is still valid - or test the functionality of methods in my component that update a formbuilder group, or determine if a formbuilder group is valid.
我想举例来说,更新我的规范中的表单的值,然后测试以查看表单是否仍然有效 - 或者测试我的组件中更新formbuilder组的方法的功能,或者确定是否为formbuilder组已验证。
2) How do I deal with the following error given that fb is a DI injection of Formbuilder in a spec? 2)如果fb是规范中的Formbuilder的DI注入,我该如何处理以下错误?
null is not an object (evaluating 'this.fb.group')
when the component is as follows: 当组件如下:
export class LoginComponent implements OnInit {
constructor( private fb: FormBuilder ) {}
ngOnInit() {
this.loginForm = this.fb.group({
'email': this.user.email,
'password': this.user.password
});
}
}
If you are using the newest version of Angular2, and want to use their testbed, here is a working spec. 如果您使用的是最新版本的Angular2,并且想要使用他们的测试平台,这里有一个工作规范。
describe('Login Component', () => {
let comp: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [LoginComponent],
providers: [
FormBuilder
]
}).compileComponents()
.then(() => {
fixture = TestBed.createComponent(LoginComponent);
comp = fixture.componentInstance;
});
}));
it('user should update from form changes', fakeAsync(() => {
const testUser = {
email: 'test@test.com',
password: '12345'
};
comp.loginForm.controls['email'].setValue(testUser.email);
comp.loginForm.controls['password'].setValue(testUser.password);
expect(comp.user).toEqual(testUser);
}));
});
I actually build a new instance of FormBuilder and give it to component under testing. 我实际上构建了一个FormBuilder的新实例,并将其提供给正在测试的组件。
sut = new LoginComponent(service, new FormBuilder());
If you want to modify any control that belongs to your ControlGroup/FormGroup then you can do it in following manner: 如果要修改属于ControlGroup / FormGroup的任何控件,则可以按以下方式执行此操作:
(<Control>sut.loginForm.controls['Name']).updateValue('Jon Doe');
You can test validity as well: 您也可以测试有效性:
sut.loginForm.valid
Update: 更新:
describe('Component', () => {
let sut: Component;
let service: Service;
beforeEach(() => {
service = new Service(null);
sut = new Component(new FormBuilder(), service);
});
it('should have object initialized', () => {
expect(sut.selectedBankAccount).toBeDefined();
});
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.