角度测试第一次返回Observable的方法

时间:2018-01-10 07:48:58

标签: javascript angular unit-testing

您好,感谢您的时间:

我正在尝试学习如何测试具有返回Observable的方法的服务。

我已经完成了Angular页面的英雄之旅教程,直到路由模块,我想对代码进行单元测试。

以下是MyHeroService:

    import {Injectable} from '@angular/core';
import {HEROES} from '../mock-heroes';
import {Hero} from '../Hero';
import {Observable} from 'rxjs/Observable';
import {of} from 'rxjs/observable/of';
import {MessageService} from '../message.service';

@Injectable()
export class MyHeroService {

  getHeroes(): Observable<Hero[]> {
    this.messageService.add('HeroService: fetched all your heroes');
    return of(HEROES);
  }

  getHero(id: number): Observable<Hero> {
    // Todo: send the message _after_ fetching the hero
    this.messageService.add(`HeroService: fetched hero id=${id}`);
    return of(HEROES.find(hero => hero.id === id));
  }

  constructor(private messageService: MessageService) {
  }

}

这是我目前正在进行的单元测试:

    import {MyHeroService} from './my-hero.service';
import {MessageService} from '../message.service';
import {async, inject} from '@angular/core/testing';

describe('heroService', () => {


  it('should return an Observable of Hero[]', async(() => {
    const myHeroService = new MyHeroService(new MessageService([]));
    myHeroService.getHero(1).subscribe(result => expect(result).toBeGreaterThan(0));
  }));
});

测试给出的结果是: enter image description here

我也读过: Unit testing an observable in Angular 2

Unit test 'success' and 'error' observable response in component for Angular 2

Angular 2 Observable Service Karma Jasmine Unit Test not working

您能否帮助我理解为什么它会 &#39;预期未定义大于0。&#39;

1 个答案:

答案 0 :(得分:0)

我认为您的问题是您没有正确注入服务(您正在导入&#39;注入&#39; @ angular / core / testing&#39;但不使用它)。

测试Angular服务的最佳方法是Angular TestBed class,其中:

  

配置和初始化单元测试的环境,并提供在单元测试中创建组件和服务的方法。

import { TestBed, inject, async} from '@angular/core/testing';
import { HeroService } from './hero.service';

describe('Testing Angular Heroes', () => {
  beforeEach(async(() => {
     TestBed.configureTestingModule({
        providers: [
           HeroService
        ]
     }).compileComponents();
  }));

  describe("Testing my awesome function", () => {
     it('should return true when I call getTrue', inject([HeroService], (heroService: HeroService) => {
        expect(heroService.getTrue()).toBe(true)
     }));
  })
});

这是一个使用Jasmine的plunkr和下面的例子: https://embed.plnkr.co/Kgkozh7gZ9GMdwHgjcph/

来源:

https://blog.thoughtram.io/angular/2016/11/28/testing-services-with-http-in-angular-2.html https://angular.io/api/core/testing/TestBed