Angular Jasmine Integration Test使用真实HTTP进行服务 [英] Angular Jasmine Integration Test with service using real HTTP
问题描述
[Angular version:2.4.5]
[Angular version: 2.4.5]
我正在尝试编写一个Angular集成组件单元测试,其中包含一个利用内置Angular HTTP的服务图书馆。我无法让我的Service类实例化:服务未定义或我得到错误:无法解析'RequestOptions'的所有参数(?)。
I'm attempting to write an Angular integration component unit test that contains a service that leverages the built-in Angular HTTP library. I cannot get my Service class to instantiate though: either the Service is undefined or I get "Error: Cannot resolve all parameters for 'RequestOptions'(?)".
I了解通常你会模拟后端(在其他单元测试中成功完成)或使用Protractor。其他SO问题引用Angular 1或者答案似乎不起作用。开始代码:
I understand that typically you'd mock the backend (have successfully done that in other unit tests) or use Protractor. Other SO questions reference Angular 1 or have answers that just don't seem to work. Starting code:
@Injectable()
export class ProjectService {
projectFeature: IProjectFeature;
constructor(private http: Http) { }
getProjects(): Observable<IProjects> {
return this.http.get("/api/Projects")
.map((response: Response) => response.json() || {})
.catch(this.handleError);
}
}
// Jasmine spec file:
beforeEach(async(() => {
TestBed.configureTestingModule({
providers: [
Http,
ProjectService, // service that leverages HTTP
ConnectionBackend
//RequestOptions // removed b/c otherwise can't find parameters error happens
],
imports: [
HttpModule
]
});
}));
it('sample test', async(() => {
var projectService = TestBed.get(ProjectService);
var comp = new ProjectComponent(projectService);
comp.ngOnInit(); // internally, calls projectService.getProjects()
expect(comp.projects[0].name).toEqual("Sample Project Name");
}));
推荐答案
HttpModule
模块应该在 TestBed
模块配置中提供。之后, Http
执行真正的XHR请求,无需额外操作,演示:
HttpModule
module should be provided in TestBed
module configuration. After that, Http
performs real XHR requests, no extra actions needed, a demo:
beforeEach(() => {
TestBed.resetTestEnvironment();
TestBed.initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting()
);
TestBed.configureTestingModule({
imports: [
HttpModule
]
});
});
it('should do XHR', async(inject([Http], (http) => {
http.get('test.json').subscribe(res => {
expect(res.json()).toBe(1);
});
})));
这篇关于Angular Jasmine Integration Test使用真实HTTP进行服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!