我有这项服务从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 - &gt; HTTP]:
StaticInjectorError(Platform:core)[CityService - &gt; HTTP]: NullInjectorError:没有Http的提供者!
如何在ng test
测试/如何展示我的城市?
这是我的第一次尝试,您可以向我推荐任何示例,或者像我的代码那样的教程吗?
答案 0 :(得分:0)
CityService
取决于3项服务,即Http
,Router
和AuthService
。你需要将它们注入测试中。
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服务进行的调用有关。