类型错误:无法读取 null 的属性“令牌”

问题描述 投票:0回答:1

我有这项服务,可以从 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);
          });
        }
      });
  }
}

现在,我已经尝试使用这段代码来测试我的服务。在这篇文章中我想知道如何测试这项服务

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

我尝试了这段代码,但显示错误:

类型错误:无法读取 null 的属性“令牌”

如何测试/如何在

ng test
中显示我的城市?

这是我的第一次尝试,你能给我推荐一些例子,或者像我的代码一样的教程吗?

angular typescript testing jasmine
1个回答
0
投票

当您没有任何当前用户时,这是可能的。 所以当没有当前用户时就返回

if(!this.auth.getCurrentUser()){
    return;
}
© www.soinside.com 2019 - 2024. All rights reserved.