【问题标题】:Angular Jasmine Integration Test with service using real HTTPAngular Jasmine 集成测试与使用真实 HTTP 的服务
【发布时间】:2017-04-26 18:04:45
【问题描述】:

[Angular 版本:2.4.5]

我正在尝试编写一个 Angular 集成组件单元测试,其中包含一个利用内置 Angular HTTP 库的服务。我无法让我的服务类实例化:服务未定义或我得到“错误:无法解析'RequestOptions'(?)的所有参数”。

我了解您通常会模拟后端(已在其他单元测试中成功完成)或使用量角器。其他 SO 问题参考 Angular 1 或有似乎不起作用的答案。起始代码:

    @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");
    })); 

【问题讨论】:

  • 你没有向 TestBed 提供 HttpModule,是吗?
  • @estus 目前没有。我已经添加了它,并更新了上面的代码。现在它失败了,说“无法读取未定义的属性响应”
  • 不可能说出你的情况出了什么问题。考虑到这是集成测试,代码可能比您发布的要多得多。无论如何,它就是这么简单(比it was in A1 简单得多)。我添加了说明它是如何完成的答案。
  • 答案对你有用吗?如果确实如此,请考虑接受它或提供一些反馈,这将有助于未来的 SO 访问者。
  • 道歉@estus!还是有困难,让我重新思考了一下我的测试策略,然后我去度假了,哈哈。公认!再次感谢。

标签: unit-testing angular typescript jasmine integration-testing


【解决方案1】:

HttpModule 模块应在TestBed 模块配置中提供。之后,Http 执行真正的 XHR 请求,无需额外操作,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);
    });
  })));

【讨论】:

    猜你喜欢
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-11
    • 2017-08-04
    • 1970-01-01
    相关资源
    最近更新 更多