15

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

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) How do I deal with the following error given that fb is a DI injection of Formbuilder in a spec?

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

2 Answers 2

26

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: '[email protected]',
      password: '12345'
    };
    comp.loginForm.controls['email'].setValue(testUser.email);
    comp.loginForm.controls['password'].setValue(testUser.password);
    expect(comp.user).toEqual(testUser);
  }));
});
Sign up to request clarification or add additional context in comments.

Comments

5

I actually build a new instance of FormBuilder and give it to component under testing.

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:

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

2 Comments

can you show me a full spec where you're implementing this? Are you declaring sut in the beforeEach?
Yes I am declaring sut in "befoereach". See my update for one my code snippet.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.