【发布时间】:2017-07-26 12:25:25
【问题描述】:
我正在探索新的 Angular HttpClientModule 并遇到莫名其妙的错误。该模块足够新,以至于我还找不到有关如何进行单元测试的任何有用信息,官方文档也没有任何示例。
该应用程序包含一个具有一种方法的服务,该方法将 URL 传递给 http.get。当我在浏览器上下文(又名ng serve)中调用此方法时,http 调用会正常执行。在单元测试的上下文中调用时,我收到以下错误:
TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
这是使用 Angular CLI 生成的最小应用程序。以下是相关代码:
app.module.ts:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, HttpClientModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts:
import { Component, OnInit } from '@angular/core';
import { TestService } from './test.service'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [TestService]
})
export class AppComponent {
title = 'app';
constructor(private testSvc: TestService) {}
ngOnInit() {
this.testSvc.executeGet('http://www.example.com');
}
}
test.service.ts:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class TestService {
constructor(private http:HttpClient) {}
executeGet(url:string) {
this.http.get(url)
.subscribe(
data => console.log('success', data),
error => console.log('error', error)
);
}
}
test.service.spec.ts:
import { HttpClient, HttpHandler } from '@angular/common/http';
import { TestBed, inject } from '@angular/core/testing';
import { TestService } from './test.service';
describe('TestService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [HttpClient, HttpHandler, TestService]
});
});
it('should executeGet', inject([TestService], (svc: TestService) => {
expect(svc.executeGet).toBeDefined();
// this is where the 'undefined' error occurs
svc.executeGet('http://www.example.com');
}));
});
非常感谢任何指导或指示。
【问题讨论】:
-
你真的需要一个真正的 HttpClientModule 吗?根据documentation - HTTP 后端需要作为良好测试实践的一部分进行模拟。
-
@AleksandrPetrovskij 我已经阅读了可用的文档。它很薄,而且 HttpClientModule 还很年轻,没有太多关于如何使用它的第三方内容。我在尝试使用 HttpClientTestingModule 时遇到了其他问题,但选择不将它们包含在这篇文章中,以使其专注于“未定义”错误。无论如何,
标签: angular