'TypeError: Cannot read property 'token' of null

I have this service that return all City from ws.

@Injectable()
export class CityService {
  constructor(private http: Http, private router: Router,
  private auth: AuthService) { }

  public getAllCity(): Observable<City[]> {
    let headers = new Headers();
    headers.append('x-access-token', this.auth.getCurrentUser().token);
    return this.http.get(Api.getUrl(Api.URLS.getAllCity), {
      headers: headers
    })
      .map((response: Response) => {
        let res = response.json();
        if (res.StatusCode === 1) {
          this.auth.logout();
        } else {
          return res.StatusDescription.map(city => {
            return new City(city);
          });
        }
      });
  }
}

Now, I have tried this code to test my service. In this post I want to know, How to test this service CityService

describe('Service: City', () => {
    let service: CityService;

    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [],
            providers: [CityService, AuthService, Http, ConnectionBackend],  
            imports: [RouterTestingModule, HttpClientTestingModule, HttpModule] 
        });
    });

    beforeEach(() => {
        service = TestBed.get(CityService);
    });

    it('#getAllCity should return real value', () => {
        expect(service.getAllCity()).toBe('real value');
    });
});

I tried this code, but show me error:

TypeError: Cannot read property 'token' of null

How to test / how to show my city in ng test?

This is my first attempt, can you suggest me any example, or tutorial like my code?



Solution 1:[1]

It is possible when you don't have any current user. So just return when there is no current user

if(!this.auth.getCurrentUser()){
    return;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nikhil Yadav