我有这项服务,可从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 component: CityService;
    let fixture: ComponentFixture<CityService>;

    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [],
            providers: [CityService]
        })
        fixture = TestBed.get(CityService);
        component = fixture.componentInstance;
    });
   it('#getAllCity should return real value', () => {
     expect(component.getAllCity()).toBe('real value');
  });
});


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


  错误:StaticInjectorError(DynamicTestModule)[CityService-> Http]:
  StaticInjectorError(平台:核心)[CityService-> Http]:
      NullInjectorError:没有Http的提供程序!


如何测试/如何在ng test中显示我的城市?

这是我的第一次尝试,您能建议我一些示例还是像我的代码这样的教程?

最佳答案

CityService取决于3个服务,即HttpRouterAuthService。您需要将它们注入测试。

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

    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [],
            providers: [CityService, AuthService],  // all all services upon which AuthService depends
            imports: [RouterTestingModule, HttpClientTestingModule],
        });
    });

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

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


https://angular.io/guide/testing-这是Angular单元测试的必读内容。
https://angular.io/guide/testing#service-tests-与测试服务有关的部分。
https://angular.io/guide/http#setup-1-与测试使用Http服务进行的调用有关。

09-20 23:15