gpt4 book ai didi

angular - 错误 : StaticInjectorError(DynamicTestModule)[CityService -> Http]: No provider for Http

转载 作者:行者123 更新时间:2023-11-28 21:07:58 25 4
gpt4 key购买 nike

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

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

Error: StaticInjectorError(DynamicTestModule)[CityService -> Http]:
StaticInjectorError(Platform: core)[CityService -> Http]: NullInjectorError: No provider for Http!

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

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

最佳答案

CityService依赖3个服务,分别是HttpRouterAuthService。您需要将它们注入(inject)测试。

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 服务进行的测试调用相关。

关于angular - 错误 : StaticInjectorError(DynamicTestModule)[CityService -> Http]: No provider for Http,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50462435/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com