首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Angular单元测试TypeError: this.http.get(...).pipe不是函数

Angular单元测试TypeError: this.http.get(...).pipe不是函数
EN

Stack Overflow用户
提问于 2018-06-20 20:40:43
回答 2查看 20.3K关注 0票数 11

我将按照这个示例为服务(来自spring应用后端的get请求) https://angular.io/guide/testing#testing-http-services进行单元测试

服务类别:

代码语言:javascript
复制
@Injectable()
export class TarifService {

  constructor(private messageService: MessageService, private http: HttpClient) { }

  public getTarifs(): Observable<Tarif[]> {
    return this.http.get<Tarif[]>(tarifffsURL).pipe(
      tap(() => {}),
      catchError(this.handleError('getTarifs', []))
    );
  }
}

单元测试

代码语言:javascript
复制
describe('TarifService', () => {

  let tarifService: TarifService;
  let httpClientSpy: { get: jasmine.Spy };
  let expectedTarifs;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [ToastrModule.forRoot(), HttpClientModule, HttpClientTestingModule],
      providers: [TarifService, HttpClient, MessageService]
    });

    httpClientSpy = jasmine.createSpyObj('HttpClient', ['get']);
    tarifService = new TarifService(<any> MessageService,<any> httpClientSpy);

  });


  it('should be created', inject([TarifService], (service: TarifService) => {
    expect(service).toBeTruthy();
  }));


  it('should return expected tarif (HttpClient called once)', () => {
    const expectedTarifs: Tarif[] =
      [{ id: 1, name: 'Tarif1', value: '20' }, { id: 2, name: 'Tarif2', value:'30' }];

    httpClientSpy.get.and.returnValue(expectedTarifs);

    tarifService.getTarifs().subscribe(
      tarifs => expect(tarifs).toEqual(expectedTarifs, 'expected tarifs'),
      fail
    );
    expect(httpClientSpy.get.calls.count()).toBe(1, 'one call');
  });
});

在运行测试时,我总是遇到这样的错误

代码语言:javascript
复制
TarifService should return expected tarif (HttpClient called once)
TypeError: this.http.get(...).pipe is not a function

这可能是什么原因呢?

EN

回答 2

Stack Overflow用户

发布于 2018-06-21 04:51:42

问题是,当您的spy被调用时,它返回一个Array,而Array没有pipe函数。您需要从spy返回一个Observable,如下所示

代码语言:javascript
复制
const expectedTarifs: Tarif[] =
  [{ id: 1, name: 'Tarif1', value: '20' }, { id: 2, name: 'Tarif2', value:'30' }];

httpClientSpy.get.and.returnValue(Observable.of(expectedTarifs));

看看returnValue是如何Observable.of(expectedTarifs)的。Observable.of创建了一个Observable,它会一个接一个地发出您指定为参数的一些值,然后发出完整的通知。See the docs

在最新版本的rxjs中,我们可以使用of运算符

代码语言:javascript
复制
import { of } from 'rxjs';

//... omitting some code here for brevity 

const expectedTarifs: Tarif[] =
  [{ id: 1, name: 'Tarif1', value: '20' }, { id: 2, name: 'Tarif2', value:'30' }];

httpClientSpy.get.and.returnValue(of(expectedTarifs));

希望能有所帮助

票数 17
EN

Stack Overflow用户

发布于 2020-04-21 22:40:22

为了让我的系统正常工作,我不得不这样做:

代码语言:javascript
复制
import { from } from 'rxjs';

然后:

代码语言:javascript
复制
return from([expectedTarifs]);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50948524

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档