title: How to Write test for login component for angular2 ( unit testing )
body: <pre><code>This is login.component.ts
  
  
  <div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>    import { Component, OnInit } from '@angular/core';
      import { Router, ActivatedRoute } from '@angular/router';
      import { FormBuilder, FormGroup, Validators } from '@angular/forms';
      import { CommonModule } from  '@angular/common';
  
  
      import { LoginUser } from './loginUser.model'
      import { UserService } from './user.service';
      import { LoaderService } from '../shared/loader.service';
  
      import 'rxjs/add/operator/toPromise';
  
      @Component({
          templateUrl: './login.component.html'
      })
      export class LoginComponent implements OnInit {
          errorMessage: string;
          loginForm: FormGroup;
          loginObj = new LoginUser();
  
          constructor(private userService: UserService, private loaderService: LoaderService, private router: Router, fb: FormBuilder) {
              this.loginForm = fb.group({
                  userName: [null, Validators.required],
                  password: [null, Validators.required]
              })
              console.log(this.loginForm);
          }
  
      test() : void{
          console.log("This is a test");
      }
          login(loginObjValue: any): void {
              if (loginObjValue.userName == null || loginObjValue.password == null) {
                  console.log('error');
              } else {
                  this.loginObj.userName = loginObjValue.userName;
                  this.loginObj.password = loginObjValue.password;
                  this.loaderService.displayLoader(true);
  
                  this.userService.login(this.loginObj)
                      .then((res) =&gt; {
                          console.log("data", res);
                          console.log("$localStorage.currentUser", localStorage);
                          let link = ['customercare/customer-ticket'];
                          this.loaderService.displayLoader(false);
  
                          this.router.navigate(link);
                      })
                      .catch(error =&gt; this.handleError(error));
              }
          }
  
          private handleError(error: any): Promise&lt;any&gt; {
              this.loaderService.displayLoader(false);
  
              if (error._body) {
                  this.errorMessage = JSON.parse(error._body).error_description;
              }
  
              console.log('An error occurred', error);
              return Promise.reject(error.message || error);
          }
  
          ngOnInit(): void {
  
  
          }
      }</code></pre>
  </div>
  </div>
  
  
  
      @Component({
          templateUrl: './login.component.html'
      })
      export class LoginComponent implements OnInit {
          errorMessage: string;
          loginForm: FormGroup;
          loginObj = new LoginUser();
  
          constructor(private userService: UserService, private loaderService: LoaderService, private router: Router, fb: FormBuilder) {
              this.loginForm = fb.group({
                  userName: [null, Validators.required],
                  password: [null, Validators.required]
              })
              console.log(this.loginForm);
          }
  
  
          login(loginObjValue: any): void {
              if (loginObjValue.userName == null || loginObjValue.password == null) {
                  console.log('error');
              } else {
                  this.loginObj.userName = loginObjValue.userName;
                  this.loginObj.password = loginObjValue.password;
                  this.loaderService.displayLoader(true);
  
                  this.userService.login(this.loginObj)
                      .then((res) =&gt; {
                          console.log("data", res);
                          console.log("$localStorage.currentUser", localStorage);
                          let link = ['customercare/customer-ticket'];
                          this.loaderService.displayLoader(false);
  
                          this.router.navigate(link);
                      })
                      .catch(error =&gt; this.handleError(error));
              }
          }
  
  
      }
  </code></pre>
  
  <blockquote>
    <p>Partial Code of userservice.ts . Please refer this code . Partial Code
    of userservice.ts . Please refer this code . Partial Code of
    userservice.ts . Please refer this code . Partial Code of
    userservice.ts . Please refer this code . Partial Code of
    userservice.ts . Please refer this code .</p>
  </blockquote>
  
  <pre><code>@Injectable()
  export class UserService {
      private URL = "";
  
      constructor(private http: Http) { }
  
      login(loginObj: LoginUser) {
  
          let body = 'userName=' + loginObj.userName + '&amp;password=' + loginObj.password + '&amp;grant_type=password';
  
          let headers = new Headers();
          headers.append('Content-Type', 'application/x-www-form-urlencoded');
  
          return this.http.post(this.URL + '/token', body, { headers: headers })
              .toPromise()
              .then((res: Response) =&gt; {
                  let data = res.json();
                  if (data &amp;&amp; data.access_token) {
                      localStorage.setItem('currentUser', JSON.stringify(data));
                  }
                  return data;
              })
      }
  
  }
  </code></pre>
  
  <p>SO FAR I HAVE WRITTEN : I am unable to call login function . Please guide me .</p>
  
  <pre><code>**
  
      describe('LoginComponent', () =&gt; {
        let component: LoginComponent;
        let UserService:UserService;
        let fixture: ComponentFixture&lt;LoginComponent&gt;;
  
      beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
          declarations: [ LoginComponent ],
          providers: [
              { provide: UserService, useValue: UserService },
                     ]
        })
  
        it('should call the login method from the UserService', 
          inject([TestBed, UserService], fakeAsync((tcb: TestBed, mockUserService: UserService) =&gt; {
            spyOn(mockUserService, 'login');
      tcb
              .createComponent(LoginComponent)
              .then((fixture: ComponentFixture&lt;LoginComponent&gt;) =&gt; {
                tick();
                 fixture.detectChanges();
                expect(mockUserService.login).toHaveBeenCalled();
              });
          }))
        );
  
      });
  
  **
  </code></pre>