0

I am writing a test case of my below auth service.

AuthService.ts

import {Subject} from 'rxjs';

import {User} from './user.model';
import {AuthData} from './auth-data.model';
import {Injectable} from '@angular/core';
import {Router} from '@angular/router';

@Injectable()
export class AuthService {

  authChange = new Subject<boolean>();

  private user: User;

  constructor(private router: Router) {
  }

  registerUser(authData: AuthData) {
    this.user = {
      email: authData.email,
      userId: Math.round(Math.random() * 10000).toString()
    };
    this.authSucessfully();
  }

  login(authData: AuthData) {
    this.user = {
      email: authData.email,
      userId: Math.round(Math.random() * 10000).toString()
    };
    this.authSucessfully();
  }

  logout() {
    this.user = null;
    this.authChange.next(false);
    this.router.navigate(['/login']);
  }

  getUser() {
    return {...this.user};
  }

  isAuth() {
    return this.user != null;
  }

  private authSucessfully() {
    this.authChange.next(true);
    this.router.navigate(['/training']);
  }
}

When I called an isAuth method I got a compile-time error. Look Attached compile-error.png enter image description here

It's because of I have not passed a parameter into it. But in AuthService class I passed Router class into the constructor.

So I tried to pass Router with 8 null parameters into that but its also giving me an error. Can you help me how to test my methods of AuthService of class if AuthService class has a constructor of Router?

enter image description here

1 Answers1

1

You can just create a mock service with jasmine:

const mockRouter: Router = jasmine.createSpyObj('Router', ['navigate’]);

Or you can configure a testing module and get the Router from it:

TestBed.configureTestingModule({
  imports: [ RouterTestingModule ]
});
const router: Router = TestBed.get(Router);

This is all described in the testing guide.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255