Angular2 FormBuilder 单元测试 [英] Angular2 FormBuilder unit testing

查看:21
本文介绍了Angular2 FormBuilder 单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于在 Angular2 中模拟 Formbuilder,我有两个问题.

I have two question in regards to mocking Formbuilder in Angular2.

1) 如何在规范中模拟 formBuilder?我们可以使用任何给定的模拟吗?例如,我想在我的规范中更新表单的值,然后测试该表单是否仍然有效 - 或者测试我的组件中更新表单构建器组的方法的功能,或者确定是否是表单构建器组有效.

1) How do I mock formBuilder in a spec? 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.

2) 如果 fb 是规范中 Formbuilder 的 DI 注入,我该如何处理以下错误?

2) How do I deal with the following error given that fb is a DI injection of Formbuilder in a spec?

null 不是对象(评估 'this.fb.group')

当组件如下:

export class LoginComponent implements OnInit {
  constructor( private fb: FormBuilder ) {}

  ngOnInit() {
    this.loginForm = this.fb.group({
      'email': this.user.email,
      'password': this.user.password
    });
  }
}

推荐答案

如果您使用的是最新版本的 Angular2,并且想使用他们的测试平台,这里有一个工作规范.

If you are using the newest version of Angular2, and want to use their testbed, here is a working spec.

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);
  }));
});

这篇关于Angular2 FormBuilder 单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆