Angular Jasmine 集成测试与使用真实 HTTP 的服务 [英] Angular Jasmine Integration Test with service using real HTTP

查看:21
本文介绍了Angular Jasmine 集成测试与使用真实 HTTP 的服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[Angular 版本:2.4.5]

[Angular version: 2.4.5]

我正在尝试编写一个 Angular 集成组件单元测试,其中包含一个利用内置 Angular HTTP 库的服务.我无法让我的服务类实例化:服务未定义或我得到错误:无法解析'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'(?)".

我了解您通常会模拟后端(已在其他单元测试中成功完成)或使用量角器.其他 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 集成测试与使用真实 HTTP 的服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆