Angular2 - Unit Testing Form Submit

I have a simple component that contains two input fields inside an element form. When you click the Submit button, it calls a function addUseron the component.

The following is a component template:

<div>
  <form [formGroup]="signupForm" (submit)="addUser($event)" role="form" class="form-horizontal">
      <label>Firstname:</label>
      <input type="text" formControlName="firstName"> 
      <label>Lastname:</label>
      <input type="text" formControlName="lastName">
      <input type="submit" id="btnSubmit" class="btn btn-primary btn-lg" value="Register" />
  </form>
</div>

The definition of the component is as follows:

@Component({
  moduleId: module.id,  
  templateUrl: 'user.component.html'  
})
export class UserComponent {

  registered = false;

  constructor(
    private router: Router,
    private fb: FormBuilder,
    public authService: AuthService) {

      this.signupForm = this.fb.group({
            'firstName': ['', Validators.required],
            'lastName': ['', Validators.required]
        });        
  }

  addUser(event: any) {
      event.preventDefault();
      this.addUserInvoked = true;
      ......
      ......
      this.authService.register(this.signupForm.value)
        .subscribe(
        (res: Response) => {
            if (res.ok) {
                this.registered = true;
            }
        },
        (error: any) => {
            this.registered = false;                                
        });
  }
}

It works great. However, in my unit test, when I try to verify that a call is made when a button is clicked on a submit button addUser. But, unfortunately, the function is addUsernot called.

Below is my unit test example

class RouterStub {
  navigateByUrl(url: string) { return url; }
}


let comp: UserComponent;
let fixture: ComponentFixture<UserComponent>;

describe('UserComponent', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [ UserComponent ],
      schemas:      [NO_ERRORS_SCHEMA]
    });
  });

  compileAndCreate();
  tests();
});

function compileAndCreate() {
  beforeEach( async(() => {
    TestBed.configureTestingModule({
      providers: [        
        { provide: Router,      useClass: RouterStub },
        { provide: AuthService, useValue: authServiceStub },
        FormBuilder
      ]
    })
    .compileComponents().then(() => {
      fixture = TestBed.createComponent(UserComponent);
      comp = fixture.componentInstance;
    });
  }));
}

function tests() {
    it('should call addUser when submitted', () => { 
        const spy = spyOn(comp, 'addUser');  

        //*************below method doesn't work and it refreshes the page***************
        //let btnSubmit = fixture.debugElement.query(By.css('#btnSubmit'));
        //btnSubmit.nativeElement.click();

        let form = fixture.debugElement.query(By.css('form'));
        form.triggerEventHandler('submit', null);
        fixture.detectChanges();

        expect(comp.addUser).toHaveBeenCalled();
        expect(authServiceStub.register).toHaveBeenCalled();
        expect(comp.registered).toBeTruthy('user registered'); 
    });

}

I tried

fixture.debugElement.query(By.css('#btnSubmit')).nativeElement.click()

and

fixture.debugElement.query(By.css('form')).triggerEventHandler('submit', null)

but I still can't call the function addUser. I have already seen the SO question here , but this is not useful either.

+4
1

, , "FormsModule" .

TestBed.configureTestingModule({
            imports: [FormsModule]
)}

?

+1

Source: https://habr.com/ru/post/1661475/


All Articles