mercredi 4 avril 2018

Angular Testing - Form instance different inside `fixture.componentInstance` and `this` inside component method?

I am trying to test a component method in Angular. It uses a reactive form.

The test is as follows.

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

The Component method login is defined as follows.

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

As visible, I have a console.log statement in the test and in the method as well.

Since the fixture.componentInstance called the login method inside the test, I would expect this to be that componentInstance and so should be the signupForm.

But they show different results. Inside the method, the values are null for form controls.

Am I doing something really silly here?

Aucun commentaire:

Enregistrer un commentaire